0

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

1 回答 1

2

我通过使用连接和分组在父模型上定义范围来实现这种事情。

例如,此范围将按答案数量(降序)对问题进行排序。

class Question
  scope :by_answer_count, -> {
    joins(:answers).reorder("count(answers.id) DESC").group(:id)
  }
end

我希望这会有所帮助。

于 2013-01-31T23:21:03.367 回答