Sql 具有多个外键的数据库链接到不同属性上的同一模型

Sql 具有多个外键的数据库链接到不同属性上的同一模型,sql,ruby-on-rails,model,foreign-keys,Sql,Ruby On Rails,Model,Foreign Keys,我很难建立我的DB关系,如果有人能给我一点帮助,我将不胜感激 我有一个表名为Person,另一个表名为Company,Company有很多人,而Person属于公司 在这里,特技公司有很多人抛出了一个名为Person的属性,还有很多人抛出了另一个名为administrator的属性 看起来像 Coca-cola = Company.new jonathan = Person.new / nicolas = Person.new Coca-cola : { person: jonathan,ni

我很难建立我的DB关系,如果有人能给我一点帮助,我将不胜感激

我有一个表名为Person,另一个表名为CompanyCompany有很多人,而Person属于公司

在这里,特技公司有很多人抛出了一个名为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公司“个人”,
:外键=>“个人id”
有很多:管理员,
:class_name=>“个人”,
:外键=>“管理员id”
结束

class-Person“公司”,
可选:true
属于:管理员,
:class_name=>“公司”,
可选:true
结束
不幸的是,这不起作用,关于什么可能导致问题的任何线索

非常感谢


乔纳森。

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

  • 属于公司的人
  • 这家公司有很多人
  • 这家公司有许多管理人员
我想你可以用下面的代码来解决:

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
class ChangePersons{其中(管理员:true)}
结束
类人<应用记录
属于:公司
结束

谢谢Gabriel的回答,是的,这是我考虑过的选择之一,但在未来,他们可能会与其他类型的人有很多其他关系,例如:员工或其他东西。
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