Home > other >  How do I mix comparison operators with a joins query in Rails?
How do I mix comparison operators with a joins query in Rails?

Time:12-09

I want to do something like this:

Aoy.joins(:member).where(season_year: session[:season_year], members: {"debut_date.year <= ?", session[:season_year]} ).order(total_points: :desc).each_with_index do |aoy, i|

"Only show Aoy entries of members that have debuted in the same year or previous to the season_year session"

  1. How do I mix comparisons and with join statement?
  2. How do I extract "year" from debut_date (debut_date.year) within the .where statement, is that possible?

thanks

CodePudding user response:

You can use YEAR() of SQL ref

Aoy.joins(:members)
   .where(season_year: session[:season_year])
   .where("YEAR(debut_date) <= ?", session[:season_year])
   .order(total_points: :desc)

CodePudding user response:

You need to write the query in SQL instead of ActiveRecord for handling this use case. For extracting year from a date field, you can use SQL YEAR method:

Aoy.joins(:member)
   .where(season_year: session[:season_year])
   .where("YEAR(members.debut_date) <= ?", session[:season_year])
   .order(total_points: :desc)
  • Related