Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Replacing Rails Components | 281

Og has finder methods reminiscent of ActiveRecord’s, but with slightly different
syntax:


>> TodoList[1]
=> #<TodoList:0x3562b1c @name="Og", @oid=1, @position=1>

>> TodoList.find_by_name 'Og'
=> #<TodoList:0x356b078 @name="Og", @oid=1, @position=1>

Thefind_with_attributesmethod (an alias forquery_by_example) has some nice syn-
tactic sugar to provide a “pattern” to match the searched-for attributes. We can view
the SQL queries being generated by setting the$DBGglobal variable totrue. For
example:


>> $DBG = true
=> true

>> TodoList.find_with_attributes :name => 'Og'
DEBUG: SELECT * FROM ogtodolist WHERE name = 'Og'
=> [#<TodoList:0x3558784 @name="Og", @oid=1, @position=1>]

>> TodoList.find_with_attributes :name => 'O%'
DEBUG: SELECT * FROM ogtodolist WHERE name LIKE 'O%'
=> [#<TodoList:0x3553874 @name="Og", @oid=1, @position=1>]

Associations work very much like in ActiveRecord. The association contents are
lazily loaded; the collection is not loaded until something is done with the data.


>> list = TodoList[1]
DEBUG: SELECT * FROM ogtodolist WHERE oid=1
=> #<TodoList:0x33e6608 @name="Og", @oid=1, @position=1>

# Note that this statement issues no query.
>> list.todo_list_items
=> #<Og::HasManyCollection:0x33e23c8 @loaded=false (...)>, oid1, position1

# Sending the collection a message such as #to_a or #map forces it to load.
>> list.todo_list_items.to_a
DEBUG: SELECT * FROM ogtodolistitem WHERE todo_list_oid = 1
=> [#<TodoListItem:0x35033d8
@name="Make Og work with ActiveSupport's Dependencies",
@todo_list_oid=1, @oid=1, @position=1>,
#<TodoListItem:0x3501c7c
@name="Autoload Orderable so that Ruby can find it",
@todo_list_oid=1, @oid=2, @position=2>]

>> list.todo_list_items.map(&:name)
DEBUG: SELECT * FROM ogtodolistitem WHERE todo_list_oid = 1
=> ["Make Og work with ActiveSupport's Dependencies",
"Autoload Orderable so that Ruby can find it"]
Free download pdf