开发者

Override as_json or to_json model class name

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-开发者_C百科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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜