Rails: 你能用 .where() 方法使用来自另一个(关联)数据库的过滤器参数创建一个新的数据库关系吗?

Rails: Can you create a new database relation using filter parameters from another (associated) database with the .where() method?

在我的例子中,我有两个模型,TournamentResult。我想为职业锦标赛结果生成一个 table,每一行都是年度结果。

我在 Tournament 模型中有一个名为 "season_year" 的专栏。

我希望能够显示关联锦标赛具有 season_year x 值(下例中的“2022”,以保留它)的所有结果简单)。

模型关联如下:

class Tournament < ApplicationRecord
has_many :results
end

class Result < ApplicationRecord
belongs_to :tournament
end

但是当我尝试以下的任何东西时,它不起作用:

<% Result.where(member_id: @member.id, tournament.season_year: "2022").each do |result| %>
    <tr>
       <td><%= result.place %></td>
       ...
    </tr>
 <% end %>

它不喜欢 tournament.season_year,因为它不是结果模型中的列。有没有一种简单的方法可以做到这一点或我应该使用的另一种方法?为什么我不能使用它与锦标赛模型的关联来过滤掉结果条目?

改变

Result.where(member_id: @member.id, tournament.season_year: "2022")

Result.joins(: tournament)
      .where(member_id: @member.id, tournaments: { season_year: "2022" })

请注意 joins 中的单数 tournament,因为这是协会的名称(在本例中为 belongs_to :tournament)。但是 where 中的复数 tournaments 因为那是实际的 table 名称。