Prev | Current Page 265 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"

Here??™s the code to do that:
module RQuery
class Conditions
def to_find_conditions
sql_strings = []
arguments = []
CHAPTER 5 ?–  BONUS FEATURES 114
columns.each do |column|
# Get the conditions of each column
sql_string, *column_arguments = column.to_find_conditions
# Append them to the rest
sql_strings << sql_string
arguments << column_arguments
end
# Build them up into the right format
full_sql_string = sql_strings.join(" AND ")
# Return them in one nice, flat array
[ full_sql_string, arguments ].flatten
end
end
end
If we try to use our new SQL generator, we should be able to create a new Conditions
object, give it a block, and be able to see the SQL that comes out, for example:
conditions = RQuery::Conditions.new do |cow|
cow.breed == breed
cow.gallons_per_day >= amount
end
conditions.to_find_conditions
# => ["breed = ? AND gallons_per_day >= ?", "Holstien", 8]
which is exactly how we want the conditions to come out! Next, we can see that when we pass
the same block to find, we??™ll get the correct result set back:
original_cows = Cow.


Pages:
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277