如何通过特定字段对has_many进行排序

Phi*_*899 6 activerecord ruby-on-rails has-many-through rails-activerecord ruby-on-rails-5

我有3种型号:member,team,和team_enrollment.结构如下:

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
Run Code Online (Sandbox Code Playgroud)

我试图做到这一点,当有人从一个成员(如此Member.first.teams)调用一个团队时,团队termination_date按照team_enrollments表中存在的属性按降序排序.我也想要它,如果它termination_date是零,它在订单的最后.我认为has_many :teams, -> {order 'team_enrollments.termination_date DESC NULLS LAST'}, through: :team_enrollments上面的那条线会起作用,但事实并非如此.它似乎对订单没有影响.我该怎么改变?

顺便说一句,我在本地和生产中使用postgres.

tea*_*her 0

我会尝试使用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
Run Code Online (Sandbox Code Playgroud)