Ruby to_json:方法参数
我正在对象上使用 to_json
方法,并尝试使 :methods
参数起作用。我的模型 (Drop) 上有一个名为 is_favorited_by_user?
的方法。此方法采用 current_user
参数,然后检查用户是否喜欢该 drop。如何通过 to_json 方法传递此参数。
render :json => @drops.to_json(:methods => :is_favorited_by_user?(current_user))
I am using the to_json
method on an object, and trying to get the :methods
argument 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_json
method.
render :json => @drops.to_json(:methods => :is_favorited_by_user?(current_user))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将
current_user
属性添加到模型中,并在执行to_json
之前设置它You can add
current_user
attribute to your model and set it before executingto_json
to_json
采用的方法并不是采用参数的方法,而只是“getter”方法。 (通常是根据您的数据库属性创建的。)请参阅此处的示例,没有传递参数:
http: //apidock.com/rails/ActiveRecord/Serialization/to_json
如果您想做一些自定义操作,您需要创建一个方法来构建所需信息的哈希值,然后将该哈希值转换为 json。
The methods
to_json
takes aren't intended to be ones that take arguments, but just "getter" methods. (Typically the ones created based on your db attributes.)See examples here, none pass arguments:
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.