【问题标题】:DB with multiple foreign keys linked to same Model on differents attributes具有多个外键的数据库链接到不同属性的同一模型
【发布时间】:2016-10-29 10:32:40
【问题描述】:

我在建立我的数据库关系时遇到了困难,如果有人能给我一点帮助,我将不胜感激!

我有一张名为 Person 的表,另一张名为 CompanyCompany has many PersonsPerson belongs_to Company >

公司 has_many Person 抛出了一个 名为 person 的属性,而 has_many Person 抛出了另一个 名为 administrator 的属性

看起来像

Coca-cola = Company.new
jonathan = Person.new / nicolas = Person.new
Coca-cola : { 
person: jonathan,nicolas
administrator: nicolas
}

我做了第一次迁移:

def change
 add_reference :persons, :person, index: true
 add_reference :persons, :administrator, index: true

 add_foreign_key :persons, :companys, column: :person_id
 add_foreign_key :persons, :companys, column: :administrator_id
end

然后我将此关系添加到我的模型中

class Company < ApplicationRecord
  has_many      :persons,
  :class_name => "Person",
  :foreign_key  => "person_id"

  has_many      :administrators,
  :class_name => "Person",
  :foreign_key  => "administrator_id"
end

class Person < ApplicationRecord
  belongs_to    :person,
  :class_name => "Company",
  optional: true

  belongs_to    :administrator,
  :class_name => "Company",
  optional: true
end

不幸的是,这不起作用,任何可能导致问题的线索?

非常感谢。

乔纳森。

【问题讨论】:

    标签: sql ruby-on-rails model foreign-keys


    【解决方案1】:

    如果我理解您的问题,请告诉我。要求是:

    • 个人所属公司
    • 公司有_很多人
    • 公司有_many管理员

    我猜你可以用下面的代码解决:

    class ChangePersons < ActiveRecord::Migration
      def change
        add_column :persons, :administrator, :boolean, default: false
      end
    end
    
    class Company < ApplicationRecord
      has_many :persons, -> { where(administrator: false) }
    
      has_many :administrators,
        class_name: "Person",
        foreign_key: "person_id",
        -> { where(administrator: true) }
    end
    
    class Person < ApplicationRecord
      belongs_to :company
    end
    

    【讨论】:

    • 感谢 Gabriel 的回答,是的,这是我考虑过的选项之一,但在未来,他们可能与其他类型的人有其他 has_many,例如:员工或其他东西。
    猜你喜欢
    • 2021-10-31
    • 2011-02-23
    • 2020-12-23
    • 2016-09-10
    • 1970-01-01
    • 2019-03-18
    • 2020-12-15
    • 1970-01-01
    • 2022-06-21
    相关资源
    最近更新 更多