渲染:json不接受选项

Ale*_*yne 27 api json ruby-on-rails

我很乐意使用,render :json但似乎不那么灵活.这是正确的方法吗?

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @things }

  #This is great
  format.json { render :text => @things.to_json(:include => :photos) }

  #This doesn't include photos
  format.json { render :json => @things, :include => :photos }
end
Run Code Online (Sandbox Code Playgroud)

Jus*_*her 39

我做过类似的事情render :json.这对我有用:

respond_to do |format|
    format.html # index.html.erb
    format.json  { render :json => @things.to_json(:include => { :photos => { :only => [:id, :url] } }) }
end
Run Code Online (Sandbox Code Playgroud)


cut*_*ion 35

我想这篇文章对你有用--Rails to_json或as_json?作者:Jonathan Julian.

主要的想法是你应该避免在控制器中使用to_json.在模型中定义as_json方法要灵活得多.

例如:

在你的事物模型中

def as_json(options={})
  super(:include => :photos)
end
Run Code Online (Sandbox Code Playgroud)

然后你可以在控制器中写一下

render :json => @things
Run Code Online (Sandbox Code Playgroud)

  • 可能想做`super(options.merge(:include =>:photos))`以保留其他可能的传入选项.你仍然会覆盖任何`:include`选项,但是...合并该键的值的逻辑会更多地涉及. (2认同)