Rails to_json:具有参数的方法 [英] Rails to_json :methods that have parameters
问题描述
我有一个包含拥有者方法的模型对象数组.此方法需要将一个参数传递给它才能起作用.我需要将模型对象序列化为json并包含owner方法的值.
I have an array of model objects that have an owner method. This method needs a parameter to be passed into it to work. I need to serialize the model objects to json and include the value of the owner method.
如何将参数传递到当前使用的
How would I go about passing the parameter into the to_json
method I currently use the
objects.to_json(:methods => :owner)
包括所有者方法,但是由于我没有传递参数,因此无法正常工作.
to include the owner method but as I am not passing the parameter it does not work.
推荐答案
注意:注释适用于Rails 2.3,尚未尝试使用Rails 3.
NOTE: Comment applies to Rails 2.3, haven't tried this w/ Rails 3.
我不相信您可以使用to_json的工作方式来完成此操作,所以我认为您有两种选择:
I don't believe you can do this w/ the way to_json works, so I think you have two options:
1.通过调用一种方法将对象的正确值存储在变量中,以准备好对象,然后在to_json调用中由所有者"方法读取该变量.
1.Prep your objects by calling a method to stash the right value away in a variable which the 'owner' method then reads during the to_json call.
2.在模型中覆盖as_json:
2.Overriding as_json in your model:
def as_json(options = {})
json = super(options)
json['owner'] = owner(options[:param_for_owner])
json
end
然后在您的to_json调用中只需传入:param_for_owner:
Then in your to_json call just pass in :param_for_owner:
objects.to_json(:param_for_owner => 'foo')
请注意,您插入值的位置将取决于ActiveRecord :: Base.include_root_in_json的配置方式.
Note that where you inject your value will depend on how your ActiveRecord::Base.include_root_in_json is configured.
这篇关于Rails to_json:具有参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!