2010-02-28 125 views
1

我是Ruby on Rails的新手,我試圖建模我的表關係。Ruby on Rails ActiveRecord:在多個其他表中有外鍵的表

爲了簡化問題,假設我有3個表:
- 客戶(ID,ADDRESS_ID,...)
- 員工(ID,ADDRESS_ID,...)
- 地址( id,...)

地址模型是否具有以下功能?

has_one :customer 
has_one :employee 

我知道在單一關係的情況下這是真的,但我找不到任何有兩個這樣的「has_one」關係的例子。

回答

2

您應該使用如下所示的多態關聯。

# 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 

現在,你可以做到以下幾點:

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

OR

employee = Employee.last 
print employee.address.street 
+0

哇,我絕對沒有做那麼遠的指南。但有一個問題。根據我讀到的,「belongs_to」關聯應該與外鍵(即員工和客戶)在桌面上,並且「has_one」關聯應該位於主鍵表上。但在你上面的例子中,你做了相反的事情。這對於多態關聯是特別的嗎? – 2010-02-28 03:48:08

+0

'Employee'和'Customer'模型具有主鍵(因此在這些模型中爲'has_one'),而'Address'模型具有外鍵(因此在此模型中爲'belongs_to')。 – 2010-02-28 05:20:19

相關問題