我很难弄清楚如何用我的模型中的范围方法来编写多层排序,它可以对模型的属性以及相关的子模型的属性进行排序。
更具体地说,我有以下模型,每个模型都是上一个模型的一个相关子模型(为了简洁起见,我排除了其他模型方法和声明):
class Course < ActiveRecord::Base
has_many :questions
# would like to write multi-layer sort here
end
class Question < ActiveRecord::Base
belongs_to :course, :counter_cache => true
has_many: :answers
end
class Answer < ActiveRecord::Base
belongs_to :question, :counter_cache => true
end我想先通过questions_count (通过我的counter_cache)对课程进行排序,然后通过answer_count对进行排序,最后通过created_at对课程进行排序,并想知道如何将所有内容组合到一个单独的作用域方法中,以放入自己的Course模型中。
谢谢。
发布于 2013-02-03 18:41:04
如图所示(使用已连接的模型创建作用域):problem: activerecord (rails3), chaining scopes with includes
在这里(使用多列排序):Ruby on Rails: how do I sort with two columns using ActiveRecord?
最后,这里(按关联模型排序):Rails 3. sort by associated model
你可以这样做:
scope :complex_sorting, lambda {
joins(:questions)
.order('questions_count DESC, question.answers_count DESC, created_at DESC')
}https://stackoverflow.com/questions/14675444
复制相似问题