Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I generate json from respond_to method in rails?

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

like image 354
Oberon Dude Avatar asked Apr 02 '10 13:04

Oberon Dude


2 Answers

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
like image 117
rogeriopvl Avatar answered Nov 15 '22 04:11

rogeriopvl


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.

like image 37
VP. Avatar answered Nov 15 '22 06:11

VP.