1

我有一个简单的查询,Rails 似乎将其解释为 fixnum,但我不确定为什么。我的代码如下所示:

@user_with_points = Point.select("sum(points) as points, user_id").order("points desc").group("user_id")
@user_with_points.each_with_index do |user_with_point, index|     

当我添加puts @user_with_points时,它显示:

#<Point:0x6360138>
#<Point:0x6322f38>

但是,我收到此错误此错误:

NoMethodError: undefined method 'each' for 75:Fixnum

添加整个代码

def self.update_overall_rank_and_points
  @user_with_points = Point.select("sum(points) as points, user_id").order("points desc").group("user_id")
  rank = 0
  points = 0

  @user_with_points.each_with_index do |user_with_point, index|           
    @user = User.find(user_with_point.user_id)
    if user_with_point.points != points
      points = user_with_point.points
      rank += 1
    end
    @user.rank = rank
    @user.points = user_with_point.points
    @user.save
  end
end
4

2 回答 2

2

您的查询返回一个标量值,它是整数的点总和。您的查询总数恰好是 75,因此出现了错误。因此,您不能each反对它,因为它不是枚举。

于 2013-03-08T03:32:09.270 回答
0

尝试:

@user_with_points = Point.sum(:points, :group => :user_id, :order => 'sum(points)')
@user_with_points.each do |user_id, points|
  #...
  user = User.find(user_id)
  if user.points != points
    puts "not equal!"
  end
end
于 2013-03-08T03:40:49.987 回答