how can I generate json from respond_to method in rails?

Oberon Dude picture Oberon Dude · Apr 2, 2010 · Viewed 55k times · Source

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...

Answer

rogeriopvl picture rogeriopvl · Apr 2, 2010

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