1

我有一个表格联系人和一个表格实体。一个实体可以有多个联系人,而同一个实体应该存储一个特殊的联系人作为主管。

我在其他地方找不到任何直接的答案,但有这样的事情:

class Entity < ApplicationRecord
  has_many :contacts
  belongs_to :entity_contact, class_name: 'Contact', foreign_key: :contact_id, optional: true
end
class Contact < ApplicationRecord
  belongs_to :entity
end
class CreateEntities < ActiveRecord::Migration[5.2]
  def change
    create_table :entities do |t|
      t.string :name
      t.references :organization, foreign_key: true
----> t.references :entity_contact

      t.timestamps
    end
  end
end

我怎样才能实现它并拥有来自 ActiveRecord 的 Entity.first.entity_contact 之类的东西?

非常感谢大家

4

2 回答 2

2

为了清楚起见,我对命名采取了一些自由:

class Entity < ApplicationRecord
  has_many :contacts
  belongs_to :supervisor, class_name: 'Contact', optional: true
end
class Contact < ApplicationRecord
  belongs_to :entity
  has_many :subordinates, class_name: 'Entity', foreign_key: :supervisor_id
end
class CreateEntities < ActiveRecord::Migration[5.2]
  def change
    create_table :entities do |t|
      t.string :name
      t.references :organization, foreign_key: true
      t.references :supervisor, foreign_key: { to_table: :contacts }
      t.timestamps
    end
  end
end
于 2019-11-19T23:35:46.040 回答
0

正如您上面的代码和请求,只需将 entity_contact 分配给 Contact 模型:

  1. 将 entity_contact_id 列添加到现有联系人表中:
    $ rails generate migration AddEntityContactToEntity entity_contact_id:integer

    调整迁移文件,如:

class AddEntityContactToEntity < ActiveRecord::Migration[5.2]
  def change
    add_reference :entities, :entity_contact, references: :contacts, index: { algorithm: :concurrently }, foreign_key: { to_table: :contacts }
  end
end

运行迁移:

$ rails db:migrate

  1. 修改模型:
class Entity < ApplicationRecord
  has_many :contacts
  belongs_to :entity_contact, class_name: :Contact, foreign_key: :entity_contact_id, optional: true
end
class Contact < ApplicationRecord
  belongs_to :entities
  has_many :subordinates, class_name: :Entity, foreign_key: :entity_contact_id
end
于 2019-12-06T12:20:25.643 回答