I'd like to modify the classname when calling to_json on an AR model.
i.e.
Book.first.to_json
#=> "{\"book\":{\"created_at\":\"2010-03-23
Book.first.to_json(:root => 'libro')
#=> "{\"libro\":{\"created_at\":\"2010-03-23
Is there an option to do this?
To be compatible with Rails 3, override as_json
instead of to_json
. It was introduced in 2.3.3:
def as_json(options={})
{ :libro => { :created_at => created_at } }
end
Make sure ActiveRecord::Base.include_root_in_json = false
. When you call to_json
, behind the scenes as_json
is used to build the data structure, and ActiveSupport::json.encode
is used to encode the data into a JSON string.
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