Donald Hughes
Donald Hughes

Reputation: 6927

Ruby on Rails ActiveRecord: table with foreign keys in more than one other table

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.

Upvotes: 1

Views: 940

Answers (1)

Harish Shetty
Harish Shetty

Reputation: 64363

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

Upvotes: 2

Related Questions