Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!