我正在尝试使用默认范围对模型 QuizCategoryWeight 施加排序顺序。目标是让@possible_answer.quiz_category_weights 按排序顺序返回权重。
更新: 我已经将问题缩小到这样一个事实,即默认范围似乎对我有用,只要它们只有一个“订单”方法,但当“包含”方法与“订单”方法链接时就不行。但是,此链接确实适用于命名范围。
会不会是我的开发环境?或者这可能是 Rails 中的一个错误?
我正在使用Windows,所以也许这就是问题所在。目前在 ruby 2.0.0p645 (2015-04-13) [i386-mingw32] 和 Rails 4.2.4 ...
以下使用 QuizCategoryWeight 上的默认范围似乎不起作用:
class QuizCategoryWeight < ActiveRecord::Base
#trying to use a default scope, but does not work
default_scope { includes(:quiz_category).order("quiz_categories.sort_order") }
belongs_to :possible_answer, inverse_of: :quiz_category_weights,
class_name: 'QuizPossibleAnswer', foreign_key: 'possible_answer_id'
belongs_to :quiz_category
end
class QuizPossibleAnswer < PossibleAnswer
has_many :quiz_category_weights,
#does not work whether the line below is used or not
->{ includes(:quiz_category).order("quiz_categories.sort_order") },
inverse_of: :possible_answer,
dependent: :destroy,
foreign_key: 'possible_answer_id'
end
class QuizCategory < ActiveRecord::Base
default_scope { order :sort_order }
end
使用命名范围,它确实有效。但是,这意味着我必须向表单构建器添加一个参数才能使用集合“f.object.quiz_category_weights.sorted”。
class QuizCategoryWeight < ActiveRecord::Base
# named scope works...
scope :sorted, ->{ includes(:quiz_category).order("quiz_categories.sort_order") }
belongs_to :possible_answer, inverse_of: :quiz_category_weights,
class_name: 'QuizPossibleAnswer', foreign_key: 'possible_answer_id'
belongs_to :quiz_category
end
class QuizPossibleAnswer < PossibleAnswer
has_many :quiz_category_weights,
inverse_of: :possible_answer,
dependent: :destroy,
foreign_key: 'possible_answer_id'
end