6

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.

Philip7899
  • 4,599
  • 4
  • 55
  • 114
  • That should work, looks like a bug. I've tried similar code and activerecord applies the ordering to the query retrieving the association. What rails version are you using? – ichigolas Aug 10 '17 at 17:42
  • Im using Rails 5 – Philip7899 Aug 10 '17 at 17:44
  • I see. What's on `ApplicationRecord`? Try to isolate the bug from the context. Your setup may have something to do with the problem. – ichigolas Aug 10 '17 at 17:48

1 Answers1

0

I would try using default_scope instead of trying to put the order clause in the association

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
teacher
  • 66
  • 4