Add virtual attribute to json output

Viewed 32826

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

8 Answers

If you want to render an array of objects with their virtual attributes, you can use

render json: many_users.as_json(methods: [:first_name, :last_name])

where first_name and last_name are virtual attributes defined on your model

Related