[英]How to do has_many and has_one between the same tables?
我有一個表格聯系人和一個表格實體。 一個實體可以有多個聯系人,而同一個實體應該存儲一個特殊的聯系人作為主管。
我在其他地方找不到任何直接的答案,但有這樣的事情:
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 之類的東西?
非常感謝大家
為了清楚起見,我對命名采取了一些自由:
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
作為您上面的代碼和請求,只需將 entity_contact 分配給 Contact model:
將 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
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.