Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add extra data to ActiveRecord records being serialized to JSON in Rails?

I'm exposing some resources via a simple API that returns JSON. I would like to inject the path to each of the resources so that the consumer need not construct them. Example of desired output for something like User.all.to_json:

users: [
  {user: {
    id: 1,
    name: 'Zaphod',
    url: 'http://domain.com/users/1.json'
  }},
  {user: {
    id: 2,
    name: 'Baron Munchausen',
    url: 'http://domain.com/users/2.json'
  }}
];

In order to generate the URL I'd like to continue using the helpers and not pollute the models with this kind of information. Is there a way to do this? Or am I better off just putting this into the model?

like image 851
Paul C Avatar asked Jan 25 '26 22:01

Paul C


1 Answers

If you have a model method you want included in the json serialization you can just use the builtin to_json call with the :methods parameter:

class Range
   def url
     # generate url
     ...
    end
end

Range.find(:first).to_json(:methods => :url)
like image 66
ry. Avatar answered Jan 28 '26 16:01

ry.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!