30

If I have a block of code like this:

def show
  @post = Post.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @post }
    end
  end

How do I add something like

format.json

Any tips, pointers, ideas gladly welcomed...

zeacuss
  • 2,563
  • 2
  • 28
  • 32
Oberon Dude
  • 455
  • 2
  • 5
  • 6

2 Answers2

69

It's just like the other formats except that you use render :json instead.

respond_to do |format|
  format.html # show.html.erb
  format.xml  { render :xml => @post }
  format.json { render :json => @post }
end
rogeriopvl
  • 51,659
  • 8
  • 55
  • 58
  • 1
    Thanks buddy - I just figured it out by reading the guide - http://guides.rubyonrails.org/layouts_and_rendering.html But you got me there faster! – Oberon Dude Apr 02 '10 at 13:31
10

or you can handle it as javascript

respond_to do |format|
  format.js { render :json { :only => :name }.to_json }
end

then you just access your action with ".js" in the end.

Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80
VP.
  • 5,122
  • 6
  • 46
  • 71
  • 1
    @Oberon Dude, for what it's worth, I've seen `format.js` a lot more than I have seen `format.json`. – maček Apr 02 '10 at 16:43
  • i didn't check. Normally by the default route, :controller/:action.:format any format is possible, but i don't know if all browsers are able to understand json mime-type.. – VP. Apr 02 '10 at 21:10