Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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-03-23 

Is there an option to do this?

like image 668
Jack Avatar asked Mar 31 '10 21:03

Jack


1 Answers

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.

like image 60
Jonathan Julian Avatar answered Oct 19 '22 06:10

Jonathan Julian