views:

37

answers:

1

This has to be a common problem, so I'm surprised that Google didn't turn up more answers. I'm working on a rails app that has several different kinds of entities, those entities by need a relation to a different entity. For example:

  1. Address: a Model that stores the details of a street address (this is my shared entity)
  2. PersonContact: a Model that includes things like home phone, cell phone and email address. This model needs to have an address associated with it
  3. DogContact: Obviously, if you want to contact a dog, you have to go to where it lives.

So, PersonContact and DogContact should have foreign keys to Address. Even, though they are really the "owning" object of Address. This would be fine, except that accepts_nested_attributes_for is counting on the foreign key being in Address to work correctly.

What's the correct strategy to keep the foreign key in Address, but have PersonContact and DogContact be the owning objects?

A: 

I believe you should use a polymorphic association.

For that you'll need to add an addressable_id and an addressable_type on your addresses table. And your models should look like:

class Address < ActiveRecord::Base
   belongs_to :addressable, :polymorphic => true    
end 

class PersonContact < ActiveRecord::Base 
   has_one :address, :as => :addressable
end

class DogContact < ActiveRecord::Base 
   has_one :address, :as => :addressable
end
j.