Join two tables with condition - ruby on rails

柔情痞子 提交于 2019-12-23 05:33:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!