Search code examples
ruby-on-rails-3activerecordrails-migrationsmodel-associations

RnR: Database normalization, rails models and associations


Ok, so I have three different objects: a person, place, and equipment. Each can have an address, in most cases multiple address and multiple phone numbers. So my thought is create the specific object tables, the have an address and a phone table. Here my question:

So typically, in my SQL world, I would just have an object_id column in the address and phone table and put a id of the object in the object id column, and then select all the address or phone records that match.

I could do this, do find_by_sql and get the records but I'd rather stay within the ActiveRecord paradigm. So does that mean I should have an id column in the table for each object, so a person_id, place_id, etc.

What's the "right" way to model this?


Solution

  • You can create polymorphic associations with activerecord, so you can add object_id and object_type to the addresses and phone_numbers tables, and specifying the associations like this:

    class Address
      belongs_to :object, :polymorphic => true
    end
    
    class PhoneNumber
      belongs_to :object, :polymorphic => true
    end
    
    class Person
      has_many :addresses, :as => :object
      has_many :phone_numbers, :as => :object
    end
    
    class Place
      has_many :addresses, :as => :object
      has_many :phone_numbers, :as => :object
    end
    
    class Equipment
      has_many :addresses, :as => :object
      has_many :phone_numbers, :as => :object
    end
    

    This way, Person.first.addresses should run a query like Addresses.where(:object_type => "Person", :object_id => Person.first.id), and vice versa for the rest of the models and associations.