Let’s say I have an app that handles a TODO list. The list has finished and unfinished items. Now I want to add two virtual attributes to the list object; the count of finished and unfinished items in the list. I also need these to be displayed in the json output.
I have two methods in my model which fetches the unfinished/finished items:
def unfinished_items
self.items.where("status = ?", false)
end
def finished_items
self.items.where("status = ?", true)
end
So, how can I get the count of these two methods in my json output?
I’m using Rails 3.1
The serialization of objects in Rails has two steps:
as_jsonis called to convert the object to a simplified Hash.to_jsonis called on theas_jsonreturn value to get the final JSON string.You generally want to leave
to_jsonalone so all you need to do is add your ownas_jsonimplementation sort of like this:You could also do it like this:
if you wanted to use different names for the method-backed values.
If you care about XML and JSON, have a look at
serializable_hash.