Ruby to_json :methods 参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2745607/
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
Ruby to_json :methods arguments
提问by James Finley
I am using the to_jsonmethod on an object, and trying to get the :methodsargument to work. I have a method on my model (Drop) called is_favorited_by_user?. This method takes an argument of the current_user, and then checks to see if the drop is favorited by the user. How can I pass this argument through the to_jsonmethod.
我to_json在对象上使用该方法,并试图使:methods参数起作用。我的模型 (Drop) 上有一个名为is_favorited_by_user?. 此方法采用 的参数current_user,然后检查用户是否喜欢该放置。我怎样才能通过to_json方法传递这个参数。
render :json => @drops.to_json(:methods => :is_favorited_by_user?(current_user))
回答by Voyta
You can add current_userattribute to your model and set it before executing to_json
您可以current_user向模型添加属性并在执行之前设置它to_json
attr_accessor :current_user
def is_favorited_by_user?(user=nil)
user ||= current_user
# rest of your code
end
@drops.current_user = current_user
render :json => @drops.to_json(:methods => :is_favorited_by_user?)
回答by James Finley
The methods to_jsontakes aren't intended to be ones that take arguments, but just "getter" methods. (Typically the ones created based on your db attributes.)
方法to_jsontake 并不打算是带参数的方法,而只是“getter”方法。(通常是根据您的 db 属性创建的。)
See examples here, none pass arguments:
请参阅此处的示例,无传递参数:
http://apidock.com/rails/ActiveRecord/Serialization/to_json
http://apidock.com/rails/ActiveRecord/Serialization/to_json
If you want to do something custom, you'll need to create a method that builds up the hash of info you want, then convert that hash to json.
如果你想做一些自定义的事情,你需要创建一个方法来构建你想要的信息的散列,然后将该散列转换为 json。

