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.
NOTE: Comment applies to Rails 2.3, haven't tried this w/ Rails 3.
I don't believe you can do this w/ the way to_json works, so I think you have two options:
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.Overriding as_json in your model:
def as_json(options = {})
json = super(options)
json['owner'] = owner(options[:param_for_owner])
json
end
Then in your to_json call just pass in :param_for_owner:
objects.to_json(:param_for_owner => 'foo')
Note that where you inject your value will depend on how your ActiveRecord::Base.include_root_in_json is configured.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With