【问题标题】:how to order of has_many through by a specific field如何通过特定字段对 has_many 进行排序
【发布时间】:2018-01-19 01:27:56
【问题描述】:

我有 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)呼叫团队时,团队按termination_date 表中存在的属性termination_date 降序排列。我也想要它,这样如果termination_date 为零,它就在订单的末尾。我认为上面的has_many :teams, -&gt; {order 'team_enrollments.termination_date DESC NULLS LAST'}, through: :team_enrollments 行会起作用,但事实并非如此。它似乎对订单没有影响。我该如何改变?

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

【问题讨论】:

  • 这应该可以,看起来像一个错误。我已经尝试过类似的代码,并且 activerecord 将排序应用于检索关联的查询。你用的是什么版本的rails?
  • 我正在使用 Rails 5
  • 我明白了。 ApplicationRecord 上有什么内容?尝试将错误与上下文隔离开来。您的设置可能与问题有关。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多