开发者

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开发者_StackOverflow中文版 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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜