how to order of has_many through by a specific field
Asked Answered
S

1

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.

Sommers answered 10/8, 2017 at 17:12 Comment(3)
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?Disclose
Im using Rails 5Sommers
I see. What's on ApplicationRecord? Try to isolate the bug from the context. Your setup may have something to do with the problem.Disclose
D
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
Decaffeinate answered 10/8, 2017 at 18:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.