I’m not sure if rails can manage this for you, but in the past when I
have two objects that access the same object I’ve created a tying table
(not sure if this is the right way to say it).
For example, an organization and an individual both can have many
addresses. While I could create an org_addresses and an ind_addresses
table I’d rather not manage two tables of addresses when I could just
create two tying tables.
This would allow me to manage addresses in one place but still be able
to access the individuals and the organizations addresses by using the
tying table.
How would one go about doing this in rails? I’ve done this many times,
but am new to rails.
one question though…if I then want to force an address to be
associated with an organization do I need to manage this or does rails
do that for me? If so, how?
For example, if I want to add a address to an existing organziation does
rails manage that for me or do I need to specifically code that
association?
The table you call a ‘tying’ table is also called a ‘join’ table. It
is part of what it is known as a ‘has and belongs to many’
relationship. The good news is that Rails handles this very easily.
Let’s take the Organizations - Addresses relationship. First you’ll
create your models and tables. You’ll end up with these tables:
organizations
addresses
Then you need to create the join table:
addresses_organizations
address_id
organization_id
Rails assumes that your join table is named after the 2 related
classes, in plural and alphabetical order.
Next you tie this up in you models:
class Organizations < ActiveRecord::Base
has_and_belongs_to_many :addresses
end
class Addresses < ActiveRecord::Base
has_and_belongs_to_many :organizations
end
That’s it for the tieing up. You can then do things like this: