Don P
Don P

Reputation: 63768

Sort a Rails model by its method

I have a question model, which has_many votes and comments.

I defined a method on the question model called engagement_score which is simply votes + comments.

class Question < ActiveRecord::base
  has_many votes
  has_many comments

  def engagement_score
    self.votes.count + self.comments.count
  end
end

How can I get all questions, sorted by engagement_score?

Question.all.order("engagement_score ASC") does not work since engagement_score is not a column in questions.

Upvotes: 0

Views: 60

Answers (2)

PGill
PGill

Reputation: 3521

You can do something like

Question.includes(:comments, :votes).order_by_engagement_score

def self.order_by_engagement_score
  sort_by |ques|
   -(ques.votes.length + ques.comments.length)
  end
end

Upvotes: 0

Chris Jeon
Chris Jeon

Reputation: 1123

If you don't mind not getting back an array, then you could probably just use sort_by.

So something like

Question.all.sort_by { |question| question.engagement_score } 

Upvotes: 2

Related Questions