Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails to_json :methods that have parameters

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.

like image 408
Craig Wanstall Avatar asked Feb 14 '11 11:02

Craig Wanstall


1 Answers

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.

like image 57
avaynshtok Avatar answered Nov 03 '22 09:11

avaynshtok