我是Ruby on Rails的新手,我正试图模拟我的表关系。
为了简化问题,假设我有3个表:
- 客户(id,address_id,...)
- 员工(id,address_id,...)
- 地址(id,...)
地址模型是否具有以下内容?
has_one :customer
has_one :employee
我知道在单一关系的情况下这是正确的,但我找不到任何有这样的“has_one”关系的例子。
答案 0 :(得分: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