Prev | Current Page 246 | Next

Brad Ediger

"Advanced Rails"

select_values(sanitize_sql(sql))
end
end
sql = %(SELECT id FROM people WHERE last_name = ?)
last_name = %(O'Reilly)
Person.select_values [sql, last_name] # => ["12", "42"]
Because ActiveRecord is not doing any of the work here, the values come across
without any type conversion (as strings here). The complete list of methods available
through the connection adapter (the ActiveRecord::Base.connection object) is listed
in the RDoc for ActiveRecord::ConnectionAdapters::DatabaseStatements.
1+N Problem
The so-called 1+N problem is characteristic of the problems that you can run into if
you are not aware of your tools. It is best illustrated with an example.
Assume that we are using the following model, which splits off a person??™s login into
a separate User model:*
class Person < ActiveRecord::Base
has_one :user
end
class User < ActiveRecord::Base
belongs_to :person
end
If you want to find the usernames of all people from Illinois, you might write this code:
logins_from_illinois = []
Person.find_all_by_state('IL').each do |person|
logins_from_illinois << person.user.login
end
Not only is this iterative code bad style in Ruby, it can be inefficient. Even the functional
version suffers from the same problem:
logins_from_illinois = Person.find_all_by_state('IL').
map{|p| p.user.login}
* This style can be very useful, especially when you need to keep track of many people who may or may not
actually be able to log in to a Rails application.


Pages:
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258