For example, both our farmers and
resellers should have an association to addresses, and since all addresses contain the same
basic data types we want this to be just one table. This is called a polymorphic association,
and Active Record supports it quite nicely.
Technically, polymorphic associations use a technique similar to single-table inheritance,
where a type column is used to specify the associated model. But it??™s not as hard as it sounds.
Let??™s walk through our farmers example to prove it. First, we need to define the address table
via our migration scripts:
create table :addresses do |t|
t.column :street, :string
t.column :city, :string
t.column :addressable_id, :integer
t.column :addressable_type, :string
end
Next, since it is on the model that contains the primary key, the polymorphic option is
really on the belongs_to method. The name of the relationship is the name that??™s used for the
:as option when specifying the other sides of the relationship. This means our models would
look something like the following:
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
end
class Farmer < ActiveRecord::Base
has_one :address, :as => :addressable
end
class Reseller < ActiveRecord::Base
has_one :address, :as => :addressable
end
Now, we have a polymorphic association that allows us to reference address data for both
farmers and resellers, all stored in one address table, as the following example demonstrates:
Example = Reseller.
Pages:
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206