daspianist
daspianist

Reputation: 5525

Difficulty sorting entries based on attributes of related models

I am having trouble implementing a feature that allows users to see questions (my model) sorted or filtered based on various attributes belonging to it (i.e. was the question answered? how many answered per question, etc), which would be based on the Question model's attributes, or that of attributes of related models to Question.

I have the following models:

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

What I would be add are sorts or filters in the controller such as "See only answered questions", where only questions that has question.accepted_answer == true. What would be the best way to achieve this? And are there any guides that I should consult on ActiveRecord filtering/sorting that I could use for future reference?

Thanks!!

Addendum

I am displaying the questions as rendered _question.html.erb and calling it via the show function of question's parent, Group (so, each Group will has_many questions)

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

Upvotes: 0

Views: 166

Answers (1)

Shane
Shane

Reputation: 514

I achieve this sort of thing by defining a scope on the parent model using joins and grouping.

For example, this scope would order the questions by number of answers (descending).

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

I hope that helps.

Upvotes: 2

Related Questions