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 に答える