How to order has_many through a specific field

I have 3 models: member, teamand 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 try to make it so that when someone calls a team from a member (s Member.first.teams), the teams are ordered in descending order by the attribute termination_datethat exists in the table team_enrollments. I also want that if it termination_dateis zero, then it is at the end of the order. I thought the above line has_many :teams, -> {order 'team_enrollments.termination_date DESC NULLS LAST'}, through: :team_enrollmentswould work, but it is not. This does not seem to affect the order. how to change it?

By the way, I use postgres locally and in production.

+6
1

default_scope , order

class Member < ApplicationRecord
  has_many :team_enrollments    
  has_many :teams, through: :team_enrollments
end

class TeamEnrollment < ApplicationRecord
  belongs_to :team
  belongs_to :member
  default_scope {order 'termination_date DESC NULLS LAST'}
end

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

All Articles