Discussion Forums
- Topic List
- Most Recent Posts
- Sign In for more options
I have a method "total_amount" in the Model which returns the sum(some field from has_many relationship)
I want this value to be present in the json for this Model, obtained by using to_json.
How can I do this?
Thanks.
You have to deal with ActiveSupport::JSON.encode operation. One way could be:
h = model.attributes h[:total_amount] = model.total_amount json_model = ActiveSupport::JSON.encode(h)
Read the documentation for #to_json. This should take you about a minute, and the answer should be obvious. Here's a link:
http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html#M001827
Thank you all. I went through the documentation page. Looks like :methods is the solution I was looking for.
