【问题标题】:Sorting has_many through on a join table property通过连接表属性对 has_many 进行排序
【发布时间】:2013-12-02 21:16:20
【问题描述】:

假设我在 rails4 应用程序中有以下内容:

class Foo < AR::Base
  has_many :foo_bar
  has_many :bar, through: :foo_bar
end

并且 foo_bar 表有一个带有数字的“排序”列。为了让事情变得更有趣,“条形”表也有一个带有数字的“排序”列。与连接表排序列同名。而且,这很重要...

class Bar < AR::Base
  default_scope -> { order(:sort) }
end

我需要在关联上有一个默认范围,例如:

foo = Foo.last
foo.bars # => List of bars, ordered by the number on the foo_bar table

我该怎么做?这意味着取消栏的范围,但只是排序

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-4 associations has-many-through


    【解决方案1】:

    您可以使用order 选项指定收集的排序顺序

    class Foo < AR::Base
      has_many :foo_bar
      has_many :bar, -> { order('foo_bar.sort') }, through: :foo_bar
    end
    

    【讨论】:

    • 谢谢。我发现了另一个问题:bar 上的默认范围。有什么想法吗?
    • 我相信 rails 4.0.X 中的 unscope 方法存在错误(查看我的测试 - gist.github.com/railscard/4ab5d5996bd867c08ec0)。我认为您当前的解决方案完全可以,但是不要忘记在更新到 4.1.0 后重构排序
    【解决方案2】:

    你可以这样做:

    foo.bars.sort(foo_bar.position)
    

    sort 将按给定属性对列表进行排序,因此请在 foo_bar 上为其指定要排序的属性。

    【讨论】:

    • 啊,是的,好点。我忘了在我的问题中说一些关键的话。我现在将对其进行编辑,但这里是:我需要将其作为关联的默认范围。
    【解决方案3】:

    我这样做是为了让它工作:

    class Foo < AR::Base
      has_many :foo_bar
      has_many :bar, through: :foo_bar
    
      def sorted_bars
        foo_bar.map(&:bar)
      end
    end
    

    由于默认范围,这对我来说太复杂了。我仍然会接受提供更优雅解决方案的答案:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 2010-11-24
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多