views:

620

answers:

2

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?

A: 

You could override the default to_json method in your model, build up a hash of the attributes you want, and then call the hash's to_json method on that.

class Book < ActiveRecord::Base

  def to_json
    { :libro => { :created_at => created_at } }.to_json
  end

end

#=> "{\"libro\":{\"created_at\":\"2010-03-26T13:45:28Z\"}}"

Or if you want all of the records attributes...

def to_json
  { :libro => self.attributes }.to_json
end
rbxbx
+4  A: 

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.

Jonathan Julian