2013-02-03 43 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