I’m trying to figure out the Rails way to model the following problem:
I have 2 tables. One (let’s call it location) contains a single
address. The other (let’s call it company) contains 3 address. I’m
trying to figure out the best way to model this. I’ve created an
address table, a set up the model as follows:
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic =>true
end
With the table defined as:
create_table :addresses do |t|
# t.column :name, :string
t.column :address_line_1, :string, :null => false
t.column :address_line_2, :string
t.column :city, :string, :null => false
t.column :state, :string, :null => false
t.column :zipcode, :string, :null => false
t.column :country, :string
t.column :addressable_id, :integer
t.column :addressable_type, :string
This would appear to give me the basic polymorphic assocation. Here is
my challange. Mapping to location seems simple:
class Location < ActiveRecord::Base
has_one :address, :as => :addressable
end
What I’m having trouble with is the company model. I’ve currently got:
class Company < ActiveRecord::Base
has_one :main_address, :as => :addressable
has_one :billing_address, :as => :addressable
has_one :alternate_billing_address, :as => :addressable
has_many :locations
end
This is clearly not correct, as each address record only has room to
point back to a single company record. This is a common problem, so I’m
sure a standard solution is out there, I just can’t find it.
Does anyone have any advise on how to model this? Add elements in the
company table point to the address table? If I do that, what should the
model look like.
I’m sure this is a newb problem, so feel free to point me to an example
or some documentation.
Thanks,
Steve