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

时间:2017-08-10 17:12:23

标签: ruby-on-rails activerecord rails-activerecord ruby-on-rails-5 has-many-through

我有3个模型:memberteamteam_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

我正在努力做到这一点,当有人从一个成员调用一个团队(所以Member.first.teams)时,团队按照{{1}上存在的属性termination_date按降序排序表。我也想要它,如果team_enrollments为零,那么它就在订单的最后。我认为上面的termination_date行可行,但事实并非如此。它似乎对订单没有影响。我该怎么改变呢?

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

1 个答案:

答案 0 :(得分: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