I'm trying to convert an ActiveRecord model to JSON in Rails, and while the to_json method generally works, the model's virtual attributes are not included. Is there a way within Rails to list not just the attributes of a model, but also it's attr_accessor and attr_reader attributes in order that all readable attributes are available when the model is converted to JSON?
Before Rails 3, use the :method option:
@model.to_json(:method => %w(some_virtual_attribute another_virtual_attribute))
In Rails 3, use :methods option
@model.to_json(:methods => %w(some_virtual_attribute another_virtual_attribute))
I did this to put the information in the model and to keep the method compatible with any way another class might call it (as_json
is called by to_json
and is supposed to return a Hash
):
class MyModel < ActiveRecord::Base
def as_json options=nil
options ||= {}
options[:methods] = ((options[:methods] || []) + [:my, :virtual, :attrs])
super options
end
end
(tested in Rails v3.0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With