我有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
我正在努力做到这一点,当有人从一个成员调用一个团队(所以Member.first.teams
)时,团队按照{{1}上存在的属性termination_date
按降序排序表。我也想要它,如果team_enrollments
为零,那么它就在订单的最后。我认为上面的termination_date
行可行,但事实并非如此。它似乎对订单没有影响。我该怎么改变呢?
顺便说一句,我在本地和生产中使用postgres。
答案 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