column :reseller_id, :integer
t.column :farmer_id, :integer
t.column :milk_price, :float
end
This should now give us a good starting point to break down each type of association.
Association Types
Active Record actually has support for a wide variety of different association types. These association
types include belongs_to, has_many, has_one, has_and_belongs_to_many, and has_many
:through. Along with these association types, there are also a handful of association modifiers
that give you full control of your Active Record models.
belongs_to
belongs_to is the most straightforward of the relationships. When you say your model belongs
to another model, it just means that only one object will be on the other side of the association.
The ID of that association is stored directly in this model. In our example, each cow belongs to
just one farmer, so the Cow model would look like the following:
class Cow < ActiveRecord::Base
belongs_to :farmer
end
CHAPTER 4 ?– CORE FEATURES OF ACTIVE RECORD 70
Referring to the cow table, you can see that one cow will only ever belong to one farmer at
a time, because the table definition for the cows contains the foreign key of the farmer to whom
it belongs.
Pages:
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190