Prev | Current Page 190 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"

In SQL, this would look something like the
following:
# this is the T-SQL version (MS SQL Server uses T-SQL)
milkprice = Farmer.find_by_sql(["Select farmers.name as farmer,
resellers.name as reseller, distributors.milk_price as price from farmer,
distributors, reseller where farmer.farmer_id = distributors.farmer_id and
distributors.reseller_id = reseller.reseller_id and farmer.farmer_id = ?",1])
milkprice.each do |rec|
puts "#{rec.farmer} sells to #{rec.reseller} for $#{rec.price} per gallon"
end
# Fred sells to Mary's Market for $0.50 per gallon
# Fred sells to Sam's Shop for $0.65 per gallon
The Active Record equivalent should look something like the following (regardless of which
version of SQL your database supports):
fred = Farmer.find(:first)
fred.distributions.each do |distribution|
puts "#{distribution.farmer.name} sells to #{distribution.reseller.name} for
$#{distribution.price} per gallon"
end
# sells to Mary's Market for $0.50 per gallon
# sells to Sam's Shop for $0.65 per gallon
As you can see, the resellers association also works as a has_many association would work.


Pages:
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202