1

我正在使用 Ruby on Rails 3.2.2。我有以下关联:

class Article < ActiveRecord::Base
  has_many :category_associations,
    :class_name => 'CategoryAssociation'

  # Note: Same as :category_associations but gets records ordered by :position.
  has_many :positioned_category_associations,
    :class_name => 'CategoryAssociation',
    :order      => :position

  has_many :categories,
    :through    => :category_associations,
    :source     => :category

  # Note: Same as :categories but gets records ordered by :position.
  has_many :positioned_categories,
    :through    => :category_associations,
    :source     => :category,
    :order      => [:category_associations => :position]
end

使用上面的代码,我可以调用@article.positioned_categories并获取按位置正确排序的类别。但是,我想使用:positioned_category_associations来检索:positioned_categories,但如果我陈述以下内容:

class Article < ActiveRecord::Base
  ...

  has_many :positioned_categories,
    :through    => :positioned_category_associations,
    :source     => :category

  # instead of
  #
  # has_many :positioned_categories,
  #   :through    => :category_associations,
  #   :source     => :category,
  #   :order      => [:category_associations => :position]
end

似乎没有按预期工作:我没有订购类别。

如何通过 检索有序类别:positioned_category_associations?可能吗?


奖励:由于:category_associations:positioned_category_associations具有几乎相同的语句(除了:order => :position),是否可以重构:positioned_category_associations语句以干燥(不要重复自己)代码?

4

0 回答 0