我在创建模型时遇到问题。我的Rails应用程序中有3个模型。
第一个模型是事件。
class Event < ApplicationRecord
has_many :items
has_many :situations
end
事件模型包含字段:id, date, team
。
第二类是物品
class Item < ApplicationRecord
belongs_to :event
has_many :situations
end
项目模型包含字段:event_id, ratio, kind, attr_1, attr_3
和数据。
第三类是情境
class Situations < ApplicationRecord
belongs_to :event
has_many :items
end
情况模型包含字段:event_id, first_item_id, second_item_id, third_item_id, percent
我需要创建3个外键(first_item_id, second_item_id, third_item_id
),这将引用Item模型中的主键。
我尝试过此代码,然后键入Item.joins(:situations)
,所以它不起作用:
class Bet < 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个大行。