开发者

Rails 3: command used to return a number now returns "nil can't be coerced into Fixnum"

开发者 https://www.devze.com 2023-03-29 04:17 出处:网络
<%= msg.average_rating %> used to return either NaN or a number: NaN if the msg had recieved no ratings or the average of all the ratings the message had recieved. But now it returns nil can\'
<%= msg.average_rating %>

used to return either NaN or a number: NaN if the msg had recieved no ratings or the average of all the ratings the message had recieved. But now it returns nil can't be coerced into Fixnum. I must have done something to break the code but I have no idea what. What is nil can't be coerced into Fixn开发者_运维知识库um and how do I fix it?

  def average_rating
      @value = 0
      self.ratings.each do |rating|
          @value = @value + rating.value
      end
      @total = self.ratings.size
      @value.to_f / @total.to_f
  end


I'd guess that rating.value is nil for some rating. Nothing else in your average_rating would produce that error.

You could try this:

self.ratings.each do |rating|
    @value = @value + rating.value.to_i
end

Calling nil.to_i gives you a zero whereas calling x.to_i for any Fixnum x gives you just x. You should also figure out why rating.value is giving you a nil when it probably shouldn't.

Also, you could use inject instead of each:

@value = self.ratings.inject(0) { |sum, rating| sum += rating.value.to_i }

but that doesn't solve your nil problem, just thought I'd mention it.


The nil problem is caused because in your controller you build a rating:

@rating = @someobject.ratings.build 

So from your db:

@someobject.ratings.count = x 

while in your controller after calling the build, you have

@someobject.ratings.count = x+1 

with parameters

#<Rating id: nil, user_id: nil, category_id: 2, value: nil, created_at: nil, updated_at: nil>

where it's value=nil.

So you can either assign average_rating to a variable before you call the build and use that in your view, use the to_i method to zero the nil, or use the sum method on the array, which will handle the nil for you.

Hope that helps......like a year later. :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号