使用范围对相关子模型中的条目进行排序

时间:2013-02-02 05:39:51

标签: ruby-on-rails ruby-on-rails-3 rails-models

我有三个相关的模型,例如以下各个模型,每个模型都是上面的模型:

class Course < ActiveRecord::Base 
  has_many :questions 
end 

class Question < ActiveRecord::Base 
  belongs_to :course
  has_many: :answers

  default_scope order: 'questions.created_at DESC'
  scope :by_answer_count, -> { #orders Questions based on its answer count
    joins(:answers).reorder("count(answers.id) DESC").group(:id)
  }
end 

class Answer < ActiveRecord::Base 
  belongs_to :question
end

我遇到的问题是:如何使用我的by_answer_count模型中的范围方法Question订购课程列表 I在index CoursesController的{​​{1}}行动中,以最少的答案显示?有没有办法利用它,或者我应该在CoursesController中编写2层向下范围方法以使过滤器工作?

谢谢!

2 个答案:

答案 0 :(得分:4)

您应该能够使用merge来实现这一目标。

class Course < ActiveRecord::Base
  scope :by_answer_count, joins(:questions).merge(Question.by_answer_count)
end

修改

似乎合并的方式存在错误。 https://github.com/rails/rails/issues/3002

您可以通过添加从课程到答案的关系来解决这个问题。所以你的课程类看起来像这样:

class Course < ActiveRecord::Base
  has_many :answers, through: :questions
  scope :by_answer_count, joins(:questions).merge(Question.by_answer_count)
end

另一种选择是在Question类中使用手动连接子句。

joins("answers ON answers.question_id = questions.id").reorder(...)

答案 1 :(得分:1)

我认为你应该在你的协会上设置一个counter_cache。就像Ryan Bates在他的第一个截屏视频中所建议的那样:http://railscasts.com/episodes/23-counter-cache-column

我认为以下内容可行:

Course.joins(:questions).order('questions.answer_count DESC')

或范围:

scope :most_answered, joins(:questions).order('questions.answer_count DESC')

它还可以作为单个查询的好处。我没有测试,但它应该工作。