您应该使用如下所示的多态关联。
# 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