gpt4 book ai didi

ruby-on-rails - 如何通过特定字段对 has_many 进行排序

转载 作者:行者123 更新时间:2023-12-04 05:53:25 25 4
gpt4 key购买 nike

我有 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),团队按属性 termination_date 降序排列。存在于 team_enrollments 上 table 。我也想要它,如果 termination_date是 nil 它在订单的末尾。我以为 has_many :teams, -> {order 'team_enrollments.termination_date DESC NULLS LAST'}, through: :team_enrollments上面的行会起作用,但不会。似乎对订单没有影响。我该如何改变?

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

最佳答案

我会尝试使用 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

关于ruby-on-rails - 如何通过特定字段对 has_many 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45619778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com