Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including a virtual attribute in the respond_with hash

I am trying to include a virtual attribute/method within a respond_to JSON hash.

The Model (employee.rb)

attr_reader :my_method

def my_method
  return "foobar"
end

The Controller (employees_controller.rb)

respond_to :json

def index
  @employees = Employee.all
  respond_with(:data => @employees, :total => Employee.all.count)
end

It is important that I have "data" as the json root for the collection of "employees" and also to include the "total" within the hash. This works well and returns a nice JSON result of all the employees and the total value.

My qustion is: How do I include the virtual attribute "my_method" for each employee within the employees hash in the JSON response?

Thanks for your time!

like image 422
primary0 Avatar asked Mar 25 '11 05:03

primary0


3 Answers

This is what worked for me.

Employee.rb

def as_json(options={})
  super.as_json(options).merge({:my_method => my_method})
end

Thanks for cmason for pointing me in the right direction. Any other solutions are welcome.

like image 110
primary0 Avatar answered Oct 19 '22 16:10

primary0


In Rails 3 one can use following

@yourmodel.to_json(methods: ['virtual_attr1', 'virtual_attr2']
like image 20
Amit Patel Avatar answered Oct 19 '22 18:10

Amit Patel


Overwriting as_json in your model should do the trick:

def as_json(options={})
  { :methods=>[:my_method] }.merge(options)
end
like image 30
cmason Avatar answered Oct 19 '22 16:10

cmason