Ruby on rails Rails 4按分级参数对用户进行排序

Ruby on rails Rails 4按分级参数对用户进行排序,ruby-on-rails,Ruby On Rails,在我正在构建的应用程序中,用户回答投票问题。用户有以下两个参数: correct_count incorrect_count 当用户正确回答问题时,他/她将在正确的_计数中加上+1。当用户回答错误时,他/她将在其错误的_计数中加上+1 我使用这两个参数计算用户的评级,公式如下: (((user.correct_count / (user.correct_count + user.incorrect_count))**2) *(user.correct_count)) 我想对排行榜页面上

在我正在构建的应用程序中,用户回答投票问题。用户有以下两个参数:

correct_count
incorrect_count 
当用户正确回答问题时,他/她将在正确的_计数中加上+1。当用户回答错误时,他/她将在其错误的_计数中加上+1

我使用这两个参数计算用户的评级,公式如下:

(((user.correct_count / (user.correct_count + user.incorrect_count))**2)
  *(user.correct_count))
我想对排行榜页面上的用户从最高评级到最低评级进行排序。我在我的用户中添加了一个名为“rating”的列,并将其添加到我的用户参数中

def user_params
  params.require(:user).permit(:name, :email, :password,
                               :password_confirmation, :correct_count,
                               :incorrect_count, :rating)
在我的用户模型中,我添加了:

def rating
  if user.correct_count == 0
    user.rating = 0.0
  else
    user.rating = (((user.correct_count.to_f / (user.correct_count.to_f + 
      user.incorrect_count.to_f))**2)*(user.correct_count.to_f)).round(2)
    end
end 

在我的用户控制器中,我有:

def index
  @users = User.highest_rating.paginate(page: params[:page])
end

到目前为止,这是行不通的。我缺少什么?

您的解决方案不起作用,因为您没有将评级存储在数据库的用户表中。如果在保存之前存储用户评级,则定义的范围将按预期工作

首先,您需要生成并运行迁移,在users表中添加一列“rating”

其次,, 在
用户
型号中:

before_save do
  if self.correct_count == 0
    self.rating = 0.0
  else
    self.rating = (((self.correct_count.to_f / (self.correct_count.to_f + 
      self.incorrect_count.to_f))**2)*(self.correct_count.to_f)).round(2)
   end
end
现在,您需要对所有用户运行save,以便在users表中填充他们的评级

User.all.each {|u| u.save}

现在,当您执行User.highest\u rating时,您应该按照用户的评级对用户进行排序。

您可以删除
self
@geeky\u sh这很有意义,谢谢您的回答。有没有办法让scope使用我的用户评级公式将用户按最高评级排序?这样,我就不必每次更新排行榜时都保存所有用户。您可以这样做,但您将无法对查询应用分页。分页是在对用户进行排序后应用的。这就是为什么我们需要在db级别对字段进行排序。如果在从数据库获取结果后进行排序,则排序将仅限于分页结果,而不是整个结果。如果在模型内计算评级,则不需要将
rating
param传递给它
User.all.each {|u| u.save}