konata = User.find(1) konata.to_json # => {"id": 1, "name": "Konata Izumi", "age": 16, "created_at": "2006/08/01", "awesome": true}
Les options :only et :except peuvent être utilisé pour limiter les attributs des models lors de la sérialization json. Par exemple :
konata.to_json(:only => [ :id, :name ]) # => {"id": 1, "name": "Konata Izumi"} konata.to_json(:except => [ :id, :created_at, :age ]) # => {"name": "Konata Izumi", "awesome": true}
Pour include des méthodes sur des models, utilisez :methods.
konata.to_json(:methods => :permalink) # => {"id": 1, "name": "Konata Izumi", "age": 16, "created_at": "2006/08/01", "awesome": true, "permalink": "1-konata-izumi"}
Pour inclure une association, utilisez :include.
konata.to_json(:include => :posts) # => {"id": 1, "name": "Konata Izumi", "age": 16, "created_at": "2006/08/01", "awesome": true, "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"}, {"id": 2, author_id: 1, "title": "So I was thinking"}]}
Plusieurs niveaux d'association peuvent être géré par to_json :
konata.to_json(:include => { :posts => { :include => { :comments => { :only => :body } }, :only => :title } }) # => {"id": 1, "name": "Konata Izumi", "age": 16, "created_at": "2006/08/01", "awesome": true, "posts": [{"comments": [{"body": "1st post!"}, {"body": "Second!"}], "title": "Welcome to the weblog"}, {"comments": [{"body": "Don't think too hard"}], "title": "So I was thinking"}]}Intégralement pompé mais traduit à partir de http://apidock.com/rails/ActiveRecord/Serialization/to_json
