Reputation: 3816
I have a model Group.
A group can have many addresses as locations. It has to have two kinds of other addresses for sure: one for a mailing address one for a billing address
So Address is a Model too, how do I have a belongs_to to the same model but with multiple ids?
i.e.
Group: mailing_address_id billing_address_id
The various locations is taken care of by a group_locations join table easy enough: id group_id address_id
But how do I use the belongs_to for the mailing_address_id and biling_address_id ??? normally it would be:
address_id (like it is in the join) but I need them to mean something.
this is an artifact of me wanting to seperate out the addresses into another table trying to keep the database relatively normalized I think it is called.
I also had a heck of a time building another kind of a join table that joins people in a group through the locations join table...but that is a diff topic I posted here:
Upvotes: 0
Views: 211
Reputation: 48246
An address is just an address so should get its own table.
A person may be located at an address and use it in a role.
Two people could live at the same address. Both for home, and one for work. Therefore:
create table addresses (
address_id int primary key,
...address info...
);
create table people (
person_id int primary key,
...person info...
);
create table people_placements (
person_id int references people(person_id),
address_id int references addresses(address_id),
address_role_id smallint references address_roles(address_role_id), /* definition elided */
primary key (person_id, address_id, addres_role_id)
);
For a sales order you would reference the people_placements table for the billing party and address. Same for shipping party and address on your sales order line items.
Upvotes: 1
Reputation: 2965
you can try :foreign_key on your relation.
look for "4.1.2.5 :foreign_key" section on here
By convention, Rails assumes that the column used to hold the foreign key on this model is the name of the association with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly
Upvotes: 1
Reputation: 1915
class Group < ActiveRecord::Base
belongs_to: billing_address, class: 'Address', foreign_key: 'billing_address_id'
belongs_to: mailing_address, class: 'Address', foreign_key: 'mailing_address_id'
end
Upvotes: 1