【问题标题】:Ruby on Rails ActiveRecord: table with foreign keys in more than one other tableRuby on Rails ActiveRecord:在多个表中具有外键的表
【发布时间】:2010-02-28 03:10:03
【问题描述】:

我是 Ruby on Rails 的新手,我正在尝试为我的表关系建模。

为了简化问题,假设我有 3 个表:
-- 客户 (id, address_id, ...)
-- 员工 (id, address_id, ...)
-- 地址(id, ...)

Address 模型会有以下内容吗?

has_one :customer
has_one :employee

我知道这在单一关系的情况下是正确的,但我找不到任何有两个这样的“has_one”关系的例子。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord model


    【解决方案1】:

    您应该使用如下所示的多态关联。

    # 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
    

    employee = Employee.last
    print employee.address.street
    

    【讨论】:

    • 哇,我绝对没有在指南中做到那么远。一个问题,不过。根据我的阅读,“belongs_to”关联应该在带有外键(即员工和客户)的表上,而“has_one”关联应该在主键表上。但在你上面的例子中,你做了相反的事情。这是多态关联特有的东西吗?
    • EmployeeCustomer 模型具有主键(因此在这些模型中为 has_one),Address 模型具有外键(因此在此模型中为 belongs_to)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多