How to add extra data to ActiveRecord entries that are serialized in JSON in Rails?

I am browsing some resources through a simple API that returns JSON. I would like to indicate the path to each of the resources so that the consumer does not create them. An example of the 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'
  }}
];

To create the URL, I would like to continue to use helpers and not pollute the models with such information. Is there any way to do this? Or am I better off just pasting this into a model?

+3
source share
2 answers

, json, to_json :methods

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

Range.find(:first).to_json(:methods => :url)
+4

: http://json.rubyforge.org/?

class Range
  def to_json(*a)
    {
      'json_class'   => self.class.name,
      'data'         => [ first, last, exclude_end? ]
    }.to_json(*a)
  end

  def self.json_create(o)
    new(*o['data'])
  end
end
0

Source: https://habr.com/ru/post/1708207/


All Articles