渲染:json不接受选项

我喜欢使用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 

我用render :json做了类似的东西render :json 。 这对我有用:

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

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

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

例如:

在你的事物模型中

 def as_json(options={}) super(:include => :photos) end 

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

 render :json => @things 

管理控制器中的复杂哈希变得非常难看。

使用Rails 3,您可以使用ActiveModel :: Serializer。 请参阅http://api.rubyonrails.org/classes/ActiveModel/Serialization.html

如果您正在做任何非平凡的事情,请参阅https://github.com/rails-api/active_model_serializers 。 我建议创建单独的序列化程序类,以避免使模型混乱并使测试更容易。

 class ThingSerializer < ActiveModel::Serializer has_many :photos attributes :name, :whatever end # ThingsController def index render :json => @things end # test it out thing = Thing.new :name => "bob" ThingSerializer.new(thing, nil).to_json 
 format.json { render @things.to_json(:include => :photos) } 

在数组的情况下我做了什么

 respond_to do |format| format.html format.json {render :json => {:medias => @medias.to_json, :total => 13000, :time => 0.0001 }} end