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

In my case I have two models, Tournament and Result. I want to generate a table for career tournament results, with each row being the yearly results.

I have a column called "season_year" in the Tournament model.

I want to be able to display all Results where the associated tournament has a season_year value of x ("2022" in the example below, to keep it simple).

Here is the model associations:

class Tournament < ApplicationRecord
has_many :results
end

class Result < ApplicationRecord
belongs_to :tournament
end

But when I try anything like the following, it does not work:

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

It doesn't like tournament.season_year since that is not a column in the Result model. Is there an easy way to do this or another method I should be using? Why can't I use its association with the Tournament model to filter out the Result entries?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source