Rails,连接两个表,每个tabe上有where子句

时间:2017-04-02 21:10:11

标签: sql ruby-on-rails join where

我是网络开发和rails的新手,我第一次尝试构建查询对象。我有一个表Players和一个表DefensiveStats,它有一个foriegn-key player_id,所以这个表中的每一行都属于一个玩家。玩家有一个字段api_player_number,这是我引用的第三方使用的id。 DefensiveStats对象有两个与此查询相关的字段 - season_number整数和week_number整数。我想要做的是构建一个带有3个参数的查询:api_player_number,season_number和week_number,它应该返回带有相应季节和周数的DefensiveStats对象,属于具有api_player_number =的玩家传递给api_player_number。

以下是我的尝试:

class DefensiveStatsWeekInSeasonQuery
def initialize(season_number, week_number, api_player_number)
    @season_number = season_number
    @week_number = week_number
    @api_player_number = api_player_number
end

# data method always returns an object or list of object, not a relation
def data
    defensive_stats = Player.where(api_player_number: @api_player_number)
    .joins(:defensive_stats)
    .where(season_number:@season_number, week_number: @week_number)
    if defensive_stats.nil?
        defensive_stats = DefensiveStats.new
    end
    defensive_stats
end

但是,这不起作用,因为它在Player类上执行第二个where子句,而不是DefensiveStats类 - >特别是" SQLite3 :: SQLException:没有这样的列:players.season_number"

如何构建此查询?谢谢!!!

1 个答案:

答案 0 :(得分:1)

Player.joins(:defensive_stats).where(players: {api_player_number: @api_player_number}, defensive_stats: {season_number: @season_number, week_number: @week_number})

Player.joins(:defensive_stats).where("players.api_player_number = ? and defensive_stats.season_number = ? and defensive_stats.week_number = ?", @api_player_number, @season_number, @week_number)