Including a model's virtual attributes when converting a record to JSON in Rails
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?
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)
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'm not sure whether it changed in Rails 3 but now you have to use the :methods option instead of :method
Other answers refer to the methods
call which returns all methods, including those which aren't attributes. An alternative approach would be to use attributes
which returns the model's attributes except that it doesn't include its virtual attributes.
If those are known, then adding something like the below to the model might help:
VIRTUAL_ATTRIBUTES = %i{foo bar baz}
VIRTUAL_ATTRIBUTES.each { |a| attr_accessor a } # create accessors
def attributes
VIRTUAL_ATTRIBUTES.each_with_object(super) { |a,h| h[a] = self.send(a) }
end
精彩评论