我有一个简单的查询,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
答案 0 :(得分:2)
您的查询返回标量值,其中点的总和为整数。您的查询总数恰好是75,因此错误。因此,你不能对each
进行反对,因为它不是枚举。
答案 1 :(得分: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