Im having trouble figuring out how to write a multi-layer sort using a scope method in my model, which can sort through the model's attributes, as well as its related child models' attributes?
To put more concretely, I have the following models, each a related child of the previous one (I excluded other model methods and declarations for brevity):
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
I would like to sort courses first by questions_count
(through my counter_cache
), then by answer_count
, and lastly by created_at
, and was wondering how I could string everything together into a single scope method to put in my Course
model.
Thanks.