Ruby on rails 排序对联接表属性有许多影响

Ruby on rails 排序对联接表属性有许多影响,ruby-on-rails,activerecord,ruby-on-rails-4,associations,has-many-through,Ruby On Rails,Activerecord,Ruby On Rails 4,Associations,Has Many Through,假设我在rails4应用程序中有以下内容: class Foo < AR::Base has_many :foo_bar has_many :bar, through: :foo_bar end 我该怎么做?这意味着取消搜索栏,但只需执行排序即可: foo.bars.sort(foo_bar.position) sort将根据给定的属性对列表进行排序,因此请在foo_栏上指定您希望排序的属性 您可以使用order选项指定集合的排序顺序 class Foo < AR::Ba

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

class Foo < AR::Base
  has_many :foo_bar
  has_many :bar, through: :foo_bar
end
我该怎么做?这意味着取消搜索栏,但只需执行排序即可:

foo.bars.sort(foo_bar.position)

sort
将根据给定的属性对列表进行排序,因此请在foo_栏上指定您希望排序的属性

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

class Foo < AR::Base
  has_many :foo_bar
  has_many :bar, -> { order('foo_bar.sort') }, through: :foo_bar
end
类Foo{order('foo_bar.sort')},通过::foo_bar 结束
我通过这样做使它工作:

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

  def sorted_bars
    foo_bar.map(&:bar)
  end
end
类Foo
由于默认的作用域,这对我来说太复杂了。我仍然会接受一个提供更优雅解决方案的答案:)

啊,是的,很好。我忘了在我的问题中说一些关键的话。我将立即编辑它,但它在这里:我需要这是一个默认范围的协会。谢谢。我发现了另一个问题:工具栏上的默认范围。有什么想法吗?我相信rails 4.0.X中的
unscope
方法有一个bug(看看我的测试-)。我认为您当前的解决方案完全可以,但不要忘记在更新到4.1.0之后重构排序
class Foo < AR::Base
  has_many :foo_bar
  has_many :bar, -> { order('foo_bar.sort') }, through: :foo_bar
end
class Foo < AR::Base
  has_many :foo_bar
  has_many :bar, through: :foo_bar

  def sorted_bars
    foo_bar.map(&:bar)
  end
end