how can I generate json from respond_to method in

2019-02-02 03:18发布

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

2条回答
太酷不给撩
2楼-- · 2019-02-02 03:50

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.

查看更多
趁早两清
3楼-- · 2019-02-02 03:53

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
查看更多
登录 后发表回答