【发布时间】:2017-10-31 16:44:08
【问题描述】:
在图片中我说Interaction,但更具体地说,这些互动是游戏中的杀戮。众所周知,杀戮有凶手和受害者。在这种情况下,我们的杀手将被称为player,我们的受害者将被称为victim。
鉴于这张图片,以下是我想要执行的一些示例查询:
Player.find(1).Interactions
> [<#Interaction id: 1>, <#Interaction id: 2>, <#Interaction id: 3>]
Interactions.where(player: Player.find(1))
> [<#Interaction id: 1>, <#Interaction id: 2>, <#Interaction id: 3>]
Interactions.where(victim: Player.find(1))
> [<#Interaction id: 4>]
Player.find(1).Interactions.where(victim: Player.find(2))
> [<#Interaction id: 2>]
Player.find(1).Interactions.count()
> 3
# Player.find(1).Interactions should (ideally) return Interactions where <#Player id: 1> is the player (not victim)
Interactions.all.count()
> 4
Player.all.count()
> 4
Player.find(2).Interactions
> []
Player.find(3).Interactions
> [ <#Interaction id: 4> ]
Player.find(4).Interactions
> []
我尝试了很多不同的关联(我已经在谷歌和 Stack Overflow 结果中挖掘了几个小时)
我认为我的Interaction 模型应该是这样的:
class Interaction < ActiveRecord::Base
belongs_to :player
has_one :victim, :class_name => 'Player'
end
还有我的Player 模特:
class Player < ActiveRecord::Base
has_man :kills
end
最后,我认为迁移应该是什么样子:
class CreatePlayerAndInteraction < ActiveRecord::Migration[5.0]
def change
create_table :players do |t|
t.string :steam_id
end
create_table :interactions do |t|
t.string :weapon
t.belongs_to :player, index: true
end
end
【问题讨论】:
-
嘿!就这么简单,谢谢。如果您做出回答,我很乐意接受。
标签: ruby activerecord sinatra sinatra-activerecord