简体   繁体   中英

Override as_json or to_json model class name

I'd like to modify the classname when calling to_json on an AR model.

ie

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.

Since 3.0.5, at least, you do now have the option of passing a :root option to the to_json call. Here is the source of the as_json method on active record now.

def as_json(options = nil)
    hash = serializable_hash(options)

    if include_root_in_json
      custom_root = options && options[:root]
      hash = { custom_root || self.class.model_name.element => hash }
    end

    hash
end

So to use this just @obj.to_json(:root => 'custom_obj')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM