开发者

how can I generate json from respond_to method in rails?

开发者 https://www.devze.com 2022-12-25 05:23 出处:网络
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

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, point开发者_如何学运维ers, ideas gladly welcomed...


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号