9

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.

1
  • How are you using the JSON? Why can't you pass parameters to #to_json? Feb 28, 2011 at 4:45

1 Answer 1

20

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.

2
  • If you want to use this as_json override method for a particular class, but do not need to include 'owner' every time, you can add "if owner[:param_for_owner]" after the json['owner']... line to make it optional. May 3, 2013 at 20:46
  • It is ok: if the methods need parameters, it means the JSON representation of the object depends on those parameters so it is normal to have a custom behavior. Otherwise, you could create another method that calls the as_json method. Eg. object.as_json_with_owner(owner) Apr 17, 2014 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.