Ruby on rails 按Rails模型的方法对其进行排序
我有一个Ruby on rails 按Rails模型的方法对其进行排序,ruby-on-rails,ruby-on-rails-4,rails-activerecord,Ruby On Rails,Ruby On Rails 4,Rails Activerecord,我有一个问题模型,它有许多投票和评论 我在问题模型上定义了一种称为参与度_得分的方法,即投票+评论 class Question < ActiveRecord::base has_many votes has_many comments def engagement_score self.votes.count + self.comments.count end end 类问题
问题
模型,它有许多投票
和评论
我在
问题
模型上定义了一种称为参与度_得分
的方法,即投票+评论
class Question < ActiveRecord::base
has_many votes
has_many comments
def engagement_score
self.votes.count + self.comments.count
end
end
类问题
我如何获得所有问题
,并按参与度评分排序
Question.all.order(“敬业度评分ASC”)
不起作用,因为敬业度评分
不是问题中的一列
如果您不介意不取回数组,那么您可以使用排序方式
大概是
Question.all.sort_by { |question| question.engagement_score }
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
你可以这样做
Question.all.sort_by { |question| question.engagement_score }
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
engagement\u score
这是一个类方法吗?这将按降序排序,你知道如何反转吗?编辑了我的答案,-(ques.vots.length+ques.comments.length)
谢谢Chris,这将按降序排序,你知道如何反转吗?这将生成n+1个查询Pavittar Gill是正确的。我的回答没有效率。用他的。