我无法实现一项功能,允许用户根据属于它的各种属性(即问题得到解答?每个问题回答多少等)来查看问题(我的模型)进行排序或过滤,这将基于关于Question
模型的属性,或相关模型属性Question
的属性。
我有以下型号:
class Question < ActiveRecord::Base
belongs_to :course
belongs_to :user
has_many :answers, inverse_of: :question
belongs_to :accepted_answer, class_name: :answer, foreign_key: :accepted_answer_id
default_scope order: 'questions.created_at DESC'
end
class Answer < ActiveRecord::Base
belongs_to :user
belongs_to :question, inverse_of: :answers
has_many :a_votes
default_scope order: 'answers.created_at DESC'
def accepted?
return false if new_record?
question.try( :accepted_answer_id ) == id
# an alternative is to use question.try( :accepted_answer ) == self
end
end
我要添加的是控制器中的排序或过滤器,例如“仅查看已回答的问题”,其中只有question.accepted_answer == true
的问题。实现这一目标的最佳方法是什么?有没有我应该参考ActiveRecord过滤/排序的指南,我可以将其用于将来的参考?
谢谢!
我正在显示问题_question.html.erb
并通过问题的父级show
Group
函数调用它(因此,每个Group
将has_many
题)
class CoursesController < ApplicationController
def show
@course = Course.find(params[:id])
# @questions = @course.questions.all this is the default selection
@questions = @course.questions.by_answer_count #maybe Im not calling the scope correctly (and sorry if I am making a noob mistake..)
end
#There are other methods not shown
end
答案 0 :(得分:2)
我通过使用连接和分组在父模型上定义范围来实现此类目的。
例如,此范围将按答案数量(降序)排序问题。
class Question
scope :by_answer_count, -> {
joins(:answers).reorder("count(answers.id) DESC").group(:id)
}
end
我希望有所帮助。