我正在尝试为Rails应用程序设置与我的模型的关联,该应用程序将管理逃生室游戏。
基本上,有三种模型。
玩家会要求玩游戏。然后,游戏管理员将在游戏开始之前批准每个请求。
我假设通过使用关联has_many:来关联模型,如下所示
这里有一个我认为应该如何设置关联的示例。
class GameMaster < ApplicationRecord
has_many :games
has_many :players, through: :games
end
class Game < ApplicationRecord
belongs_to :game_master
belongs_to :player
end
class Player < ApplicationRecord
has_many :games
has_many :game_masters, through: :games
end如果我走对了路,请告诉我
发布于 2018-07-27 10:26:16
因为一个游戏可以有多个玩家,一个玩家可以有多个游戏,所以你需要一个在一个组合键中组合game_id和player_id的表关联。
通过这种方式,玩家可以在许多游戏中请求玩。
游戏大师同样需要,如果一个游戏可以有多个大师,可以批准玩家的请求。
PlayerGame将设置游戏的玩家,MasterGame将设置游戏的主控者:
因此,您必须具备:
class Player < ApplicationRecord
has_many :player_games
has_many :games, through: :player_games
end
class Master < ApplicationRecord
has_many :master_games
has_many :games, through: :master_games
end
class Game < ApplicationRecord
has_many :player_games
has_many :players, through: :player_games
has_many :master_games
has_many :masters, through: :master_games
end
class PlayerGame < ApplicationRecord
belongs_to :player
belongs_to :game
end
class MasterGame < ApplicationRecord
belongs_to :master
belongs_to :game
end如果用户可以成为主用户,情况可能会有所不同。让我知道。建议,绘制一个易于理解的实体关系模型。
https://stackoverflow.com/questions/51548527
复制相似问题