Ruby-on-rails render :json 不接受选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/611931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
render :json does not accept options
提问by Alex Wayne
I'd love to use render :jsonbut it seems its not as flexible. Whats the right way to do this?
我很想使用,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
回答by Justin Gallagher
I've done something similar with render :json. This is what worked for me:
我做过类似的事情render :json。这对我有用:
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @things.to_json(:include => { :photos => { :only => [:id, :url] } }) }
end
回答by cutalion
I guess this article can be useful for you - Rails to_json or as_json?by Jonathan Julian.
我想这篇文章可能对你有用 - Rails to_json 还是 as_json?作者:乔纳森·朱利安
The main thought is that you should avoid using to_json in controllers. It is much more flexible to define as_json method in your model.
主要思想是你应该避免在控制器中使用 to_json 。在模型中定义 as_json 方法要灵活得多。
For instance:
例如:
In your Thing model
在你的事物模型中
def as_json(options={})
super(:include => :photos)
end
And then you can write in your controller just
然后你可以在你的控制器中写
render :json => @things
回答by tee
Managing complex hashes in your controllers gets ugly fast.
在控制器中管理复杂的哈希值很快就会变得丑陋。
With Rails 3, you can use ActiveModel::Serializer. See http://api.rubyonrails.org/classes/ActiveModel/Serialization.html
在 Rails 3 中,您可以使用 ActiveModel::Serializer。请参阅http://api.rubyonrails.org/classes/ActiveModel/Serialization.html
If you're doing anything non-trivial, see https://github.com/rails-api/active_model_serializers. I recommend creating separate serializer classes to avoid cluttering your models and make tests easier.
如果您正在做任何重要的事情,请参阅 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
回答by Bank
in case of array what I done is
在数组的情况下,我所做的是
respond_to do |format|
format.html
format.json {render :json => {:medias => @medias.to_json, :total => 13000, :time => 0.0001 }}
end
回答by Darren
format.json { render @things.to_json(:include => :photos) }

