我想加入2桌,游戏和game_logs。我这样做了:
game_joins = Game.joins(:game_logs)
有效。但问题是我只想加入player_id = 1(例如)的地方。列player_id只能在表game_logs中找到。所以,当我这样做时:
game_joins = Game.joins(:game_logs).where(:player_id => 1)
无法找到列player_id,因为
Game.joins(:game_logs)
将导致:
SELECT games.* FROM games
INNER JOIN game_logs ON game_logs.game_id= game.id
所以,问题是我有什么可能使用表game_logs中的条件过滤game_joins。我希望我解释得很好。谢谢
答案 0 :(得分:3)
game_joins = Game.joins(:game_logs).where(:game_logs => { :player_id => 1 })
答案 1 :(得分:1)
在模型GameLog中你需要
belongs_to :game
在模型游戏中你需要
has_many :game_logs
然后一种修改查询的方法是
game_joins = Game.joins("left join game_logs on games.id = game_logs.game_id").where("game_logs.player_id = 1").all
或者您可以使用
game_joins = Game.joins(:game_logs).where("game_logs.player_id = 1").all