In the world of SQL, the cow table foreign key is the ???one??? side of a one-to-one or
one-to-many relationship. With this association defined, we can fulfill the following real-world
requirement: get the farmer who owns a given cow.
Here, we are starting with the cow table, and we know which cow we want. We need to join
the farmer table based on farmer_id so that we can see the name of the farmer who owns the
cow. This means we want to do a left join (we want all the data from the cow table for this cow
and we want the farmer??™s name from the farmer table). With SQL, our join query would look
something like the following:
# this is the T-SQL version (MS SQL Server uses T-SQL)
cow = Cow.find_by_sql("Select farmer.name as farmername from
cow inner join farmer on cow.farmer_id = farmer.farmer_id")
puts cow[0].farmername # => "Farmer Fred"
The Active Record equivalent should look something like the following (regardless of which
version of SQL your database supports!):
cow = Cow.find(:first)
cow.farmer.name # => "Farmer Fred"
As you can see, with this simple association, you automatically have access to all the attributes
of the associated table (farmer).
Pages:
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191