[英]Multiple foreign keys in ruby on rails
我在創建模型時遇到問題。 我的 Rails 應用程序中有 3 個模型。
第一個 model 是事件。
class Event < ApplicationRecord
has_many :items
has_many :situations
end
事件 model 包含字段: id, date, team
。
第二個 class 是 Items
class Item < ApplicationRecord
belongs_to :event
has_many :situations
end
項目 model 包含字段: event_id, ratio, kind, attr_1, attr_3
和數據。
第三個 class 是情況
class Situations < ApplicationRecord
belongs_to :event
has_many :items
end
情況 model 包含字段: event_id, first_item_id, second_item_id, third_item_id, percent
我需要創建 3 個外鍵( first_item_id, second_item_id, third_item_id
),它們將引用 Item model 中的主鍵。
我已經嘗試過這段代碼,然后輸入Item.joins(:situations)
,所以它不起作用:
class Item < ApplicationRecord
belongs_to :event
has_many :situations, class_name: 'Situation', foreign_key: ['first_item_id',
'second_item_id', 'third_item_id']
end
例如:
Situations table:
id event_id first_item_id second_item_id third_item_id percent
1 1001 2323 2324 2325 3%
2 1001 2323 2525 2525
Event table:
id date team
1001 02/10/2019 'Chicago - New York'
Item table:
id event_id ratio kind attr_1 att_3
2323 1001 2.3 test 12 15
2323 1001 7.7 next 52 55
2324 1001 8.7 nsext 5 18
2325 1001 1.1 ext 4 58
並且我想在執行 Item.joins(:situations) 后獲得 2 大行,其中包含來自事件、項目和情況表的所有字段的數據。
當我們談論關聯時,我們必須為各個鍵定義關聯,
class Event < ApplicationRecord
has_many :items
has_many :first_for_situations, through: :items
has_many :second_for_situations, through: :items
has_many :third_for_situations, through: :items
end
class Item < ApplicationRecord
belongs_to :event
has_many :first_for_situations, class_name: 'Item', foreign_key: :first_item_id
has_many :second_for_situations, class_name: 'Item', foreign_key: :second_item_id
has_many :third_for_situations, class_name: 'Item', foreign_key: :third_item_id
end
class Situation < ApplicationRecord
belongs_to :event
belongs_to :first_item, class_name: 'Item', foreign_key: :first_item_id
belongs_to :second_item, class_name: 'Item', foreign_key: :second_item_id
belongs_to :third_item, class_name: 'Item', foreign_key: :third_item_id
end
如果要獲取多個鍵的ActiveRecord::Relation
object,請使用 class 方法,如下所示,
class Item < ApplicationRecord
belongs_to :event
def situations
where(first_item_id: id, second_item_id: id, third_item_id: id)
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.