Prev | Current Page 184 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"


Again, we are starting with the farmer table, and we know which farmer we want information
about; we just want to get the name of the tractor that this farmer owns. The SQL query
for this example would look something like the following:
# this is the T-SQL version (MS SQL Server uses T-SQL)
tractor = Farmer.find_by_sql(["Select tractor.name as tractorname from
farmer inner join tractors on farmer.farmer_id = tractors.farmer_id
where farmer_id = ?",1])
tractors.each do |rec|
print rec.cowname
end
# => Big Red
The Active Record equivalent should look something like the following (regardless of
which version of SQL your database supports):
tractor = Farmer.find(1)
tractor.tractors each do |tractor|
print tractor.name
end
# => Big Red
As you can see, the code is identical to the has_many code; it??™s really only the results that
are limited.
?– Note The difference, basically, between has_many and has_one is the same as the difference between
find(:all) and find(:first).
CHAPTER 4 ?–  CORE FEATURES OF ACTIVE RECORD 73
has_and_belongs_to_many
Our tractor example showed a serious design flaw in that each tractor type could only be
owned by one farmer and each farmer could only own one tractor at a time.


Pages:
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196