2013-02-03 26 views
1

我在模型中使用范围方法编写多层排序时遇到困难,它可以对模型的属性以及相关的子模型的属性进行排序?Rails模型中的多层排序

说得更加具体,我有以下的车型,前一个的每一个关子(我排除了简洁其他模型的方法和声明):

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模型。

谢谢。

回答

4

正如在这里看到(创建与连接模型一个范围内):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') 
} 
+0

非常丰富,并感谢您提供的链接! – daspianist

+0

如上所示在代码中键入会导致“尝试创建没有块的Proc对象”错误。在看到类似的问题后,我将代码重新格式化为'scope:by_most_popular,lambda {| course | joins(:question).order('questions_count DESC,question.answers_count DESC,created_at DESC') }'。然而,现在Ruby抱怨说“参数数量错误(0代表1)” – daspianist

+0

更新了我的答案以用大括号替换“do ... end”。你对“错误的参数错误数量(0为1)”有更多的精度吗? – Raindal