yellowreign
yellowreign

Reputation: 3638

Rails Fixnum Error

I have a simple query that Rails seems to be interpreting as a fixnum, but I'm not sure why. My code looks like this:

@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|     

When I add puts @user_with_points, it shows:

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

However, I'm receiving this error this error:

NoMethodError: undefined method 'each' for 75:Fixnum

adding Entire Code

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

Upvotes: 1

Views: 582

Answers (2)

xdazz
xdazz

Reputation: 160833

Try:

@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

Upvotes: 0

Richard Brown
Richard Brown

Reputation: 11436

Your query is returning a scalar value which the sum of points as an integer. The total of your query happens to be 75, hence the error. Therefore you can't do an each against it since it's not an enumeration.

Upvotes: 2

Related Questions