我无法实现一项功能,该功能允许用户查看根据属于它的各种属性排序或过滤的问题(我的模型)(即问题是否已回答?每个问题回答了多少等),这将基于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