Foreign key in has_one instead of belongs_to

Hi all,

Is it possible to have the foreign key in the table where its model
have has_one instead of belongs_to? Let me explain. I have a lot of
tables that use the table Addresses, like Customer, Billing, etc, but
I don’t want all that foreign keys in the Address table (customer_id,
billing_id and so on).

Switching has_one and belongs_to its not the ideal solution I guess,
because it would not be possible to save address automatically when
saving Customer, or set Address as dependent of Customer (:dependent
=> delete). Whats the best solution here?

Thanks for any help!

Henrique wrote:

Hi all,

Is it possible to have the foreign key in the table where its model
have has_one instead of belongs_to? Let me explain. I have a lot of
tables that use the table Addresses, like Customer, Billing, etc, but
I don’t want all that foreign keys in the Address table (customer_id,
billing_id and so on).

Switching has_one and belongs_to its not the ideal solution I guess,
because it would not be possible to save address automatically when
saving Customer, or set Address as dependent of Customer (:dependent
=> delete). Whats the best solution here?

You can certainly move the foreign key into the other tables, however
you’d need a has_one association in Address for each class that has a
belongs_to :address. It would be simpler to have belongs_to in the
Address class with a :polymorphic => :addressable option, which would
solve the problem of having many foreign keys in that table.


Josh S.
http://blog.hasmanythrough.com