您應該使用如下所示的多態關聯。
# 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
哇,我絕對沒有做那麼遠的指南。但有一個問題。根據我讀到的,「belongs_to」關聯應該與外鍵(即員工和客戶)在桌面上,並且「has_one」關聯應該位於主鍵表上。但在你上面的例子中,你做了相反的事情。這對於多態關聯是特別的嗎? – 2010-02-28 03:48:08
'Employee'和'Customer'模型具有主鍵(因此在這些模型中爲'has_one'),而'Address'模型具有外鍵(因此在此模型中爲'belongs_to')。 – 2010-02-28 05:20:19