Search code examples
ruby-on-railsrubyruby-on-rails-5

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?


Solution

  • Change

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

    to

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

    Note the singular tournament in the joins because that is the name of the association (belongs_to :tournament in this case). But the plural tournaments in the where because that is the actual table name.