问题
I wanna join 2 table, games and game_logs. I did it this:
game_joins = Game.joins(:game_logs)
It worked. But the thing is I only want to join where the player_id = 1(for example). Column player_id can only be found in table game_logs. So, when I do like this:
game_joins = Game.joins(:game_logs).where(:player_id => 1)
Column player_id can't be found, because
Game.joins(:game_logs)
will result :
SELECT games.* FROM games
INNER JOIN game_logs ON game_logs.game_id= game.id
So, the question is what is the possibility I have to filter game_joins with the condition from table game_logs. I hope I explain it well enough. Thanks
回答1:
game_joins = Game.joins(:game_logs).where(:game_logs => { :player_id => 1 })
回答2:
In model GameLog you need
belongs_to :game
In model Game you need
has_many :game_logs
Then one way to modify your query is
game_joins = Game.joins("left join game_logs on games.id = game_logs.game_id").where("game_logs.player_id = 1").all
or you can use
game_joins = Game.joins(:game_logs).where("game_logs.player_id = 1").all
来源:https://stackoverflow.com/questions/18846583/join-two-tables-with-condition-ruby-on-rails