views:

250

answers:

1

I'm new to Ruby on Rails and I'm trying to model my table relationships.

To simplify the problem, let's say I have 3 tables:
-- Customer (id, address_id, ...)
-- Employee (id, address_id, ...)
-- Address (id, ...)

Would the Address model have the following?

has_one :customer
has_one :employee

I know this is true in the case of a single relationship, but I couldn't find any examples where there were two "has_one" relationships like that.

+2  A: 

You should use polymorphic associations as shown below.

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

# Customer model
class Customer < ActiveRecord::Base
  has_one :address, :as => :addressable
end

# Employee model
class Employee < ActiveRecord::Base
  has_one :address, :as => :addressable
end

# Migration script for `addresses` table
class CreateAddresses < ActiveRecord::Migration
  def self.up
    create_table :addresses, :force => true do |t|
      t.references :addressable, :polymorphic => true, :null => false

      # add other address fields

      t.timestamps      
    end

    add_index :addresses, ["addressable_id", "addressable_type"], :name => "fk_addressable"

end

Now you can do the following:

customer = Customer.new
customer.address = Address.new(:street => "ABC", :city => "SF", :zip => "46646")
customer.save

OR

employee = Employee.last
print employee.address.street
KandadaBoggu
Wow, I definitely haven't made it that far in the guides. One question, though. From what I've read, the "belongs_to" association should be on the table with the foreign key (ie, Employee and Customer) and the "has_one" association should be on the primary key table. But in your example above, you've done the opposite. Is that something particular to polymorphic associations?
Donald Hughes
The `Employee` and the `Customer` models have the primary key(hence `has_one` in these model) and `Address` model has the foreign key(hence `belongs_to` in this model).
KandadaBoggu