Slide 31
Slide 31 text
JSON in ActiveRecord
class User < ActiveRecord::Base
JSON_ATTRS = ['id','email','uuid'].freeze
has_one :inbox
has_one :trashbox
has_many :columns, :order => 'position'
has_many :boxes, :through => :columns
:order => 'columns.position,
boxes.position'
def as_json(options={})
attributes.slice(*JSON_ATTRS).merge(
:inbox => inbox,
:trashbox => trashbox,
:columns => columns
)
end
end
>> Bookmark.find(27726).to_json
=> "{\
"position\
":1,\
"name\
":\
"Prototype
Framework\
",\
"url\
":\
"http:/
/prototypejs.org/\
",
\
"owner_id\
":7181,\
"id\
":27726,\
"owner_type\
":
\
"Box\
"}"
>> Box.find(7181).to_json
=> "{\
"position\
":4,\
"title\
":\
"JavaScript Refs\
",
\
"collapsed\
":true,\
"id\
":7181,\
"bookmarks\
":
[{\
"position\
":1,\
"name\
":\
"Prototype Framework
\
",\
"url\
":\
"http:/
/prototypejs.org/\
",\
"owner_id\
":
7181,\
"id\
":27726,\
"owner_type\
":\
"Box\
"},
{\
"position\
":2,\
"name\
":\
"Scriptaclous
Framework\
",\
"url\
":\
"http:/
/script.aculo.us/\
",
\
"owner_id\
":7181,\
"id\
":27725,\
"owner_type\
":
\
"Box\
"},{\
"position\
":3,\
"name\
":\
"DevGuru
(JavaScript)\
",\
"url\
":\
"http:/
/
www.devguru.com/technologies/javascript/
home.asp\
",\
"owner_id\
":7181,\
"id\
":
27724,\
"owner_type\
":\
"Box\
"},{\
"position\
":
4,\
"name\
":\
"Dean Edwards Base.js\
",\
"url\
":
\
"http:/
/dean.edwards.name/weblog/
2006/03/base/\
",\
"owner_id\
":7181,\
"id\
":
27723,\
"owner_type\
":\
"Box\
"}],\
"column_id\
":
3538,\
"style\
":\
"yellow_green\
"}"
Wednesday, July 14, 2010