简体   繁体   English

按其方法对Rails模型进行排序

[英]Sort a Rails model by its method

I have a question model, which has_many votes and comments . 我有一个question模型,它具有很多votescomments

I defined a method on the question model called engagement_score which is simply votes + comments . 我在question模型上定义了一个名为“ engagement_score的方法,该方法只是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 ? 我如何获得所有questions (按engagement_score排序)?

Question.all.order("engagement_score ASC") does not work since engagement_score is not a column in questions . Question.all.order("engagement_score ASC")不起作用,因为engagement_score不是questions一列。

If you don't mind not getting back an array, then you could probably just use sort_by. 如果您不介意不返回数组,则可以使用sort_by。

So something like 所以像

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM