Prev | Current Page 406 | Next

Brad Ediger

"Advanced Rails"

select{|u| u.salary > 50_000}.map(&:name)
# SELECT * FROM users WHERE (users.`salary` > 50000)
=> ["David", "Jamis", "fixture_3", "fixture_4", "fixture_5", "fixture_6",
"fixture_7", "fixture_8", "fixture_9", "fixture_10", "admin", "Goofy"]
Since the Query object being passed around contains all information necessary to run
the query, additional methods chained onto it can actually modify the query as
needed. For example, asking the Query object for its length changes the query to
select only a count instead of a full list of columns:
>> User.select{|u| u.salary > 50_000}.length
# SELECT count(*) AS count_all FROM users WHERE (users.`salary` > 50000)
=> 12
These methods can be chained, augmenting the query as they progress. For example,
the sort_by method adds an ORDER BY clause:
>> User.select{|u| u.salary > 50_000}.sort_by{|u| u.name}.map(&:name)
# SELECT * FROM users WHERE (users.`salary` > 50000) ORDER BY users.name
=> ["admin", "David", "fixture_10", "fixture_3", "fixture_4", "fixture_5",
"fixture_6", "fixture_7", "fixture_8", "fixture_9", "Goofy", "Jamis"]
* Currently, the only way to fetch the latest Ambition source is using Git, a decentralized version control system.
We cover the decentralized paradigm in Chapter 10, but for now you can fetch Git from http://git.or.cz/.
Replacing Rails Components | 275
The Query object has a to_hash and a (mostly functional) to_sql method, which help
debug the SQL queries and conditions being generated:
>> User.


Pages:
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418