how to order of has_many through by a specific field

Viewed 429

I have 3 models: member, team, and team_enrollment. The structure is as follows:

class Member < ApplicationRecord
  has_many :team_enrollments    
  has_many :teams, -> {order 'team_enrollments.termination_date DESC NULLS LAST'}, through: :team_enrollments
end

class TeamEnrollment < ApplicationRecord
  belongs_to :team
  belongs_to :member
end

class Team < ApplicationRecord
    has_many :team_enrollments
    has_many :members, through: :team_enrollments
end

I am trying to make it so that when someone calls a team from a member(so Member.first.teams), the teams are ordered in descending order by the attribute termination_date which exists on the team_enrollments table. I also want it so that if termination_date is nil that it is at the end of the order. I thought that the has_many :teams, -> {order 'team_enrollments.termination_date DESC NULLS LAST'}, through: :team_enrollments line above would work but it does not. It seems to have no affect on the order. how do I change this?

By the way, i am using postgres locally and in production.

1 Answers
Related