I am having that problem when I update my konkurrencer the do_foobar is called. The problem is that the konkurrancer have no ratings. And I get a off course a开发者_C百科 ZeroDivisionerror.
What is the best solution to solve this kind of problem?
My model:
before_update :do_foobar
def do_foobar
self.rating = (rating_score/ratings)
end
self.rating = (ratings == 0) ? nil : rating_score/ratings
or
self.rating = rating_score/ratings rescue nil
if you always do
self.rating = 0 if ratings == 0 else (rating_score/ratings)
A simpler way would be to catch the error on the spot.
rating = rating_score - ratings rescue 0
This will instantly catch the ZeroDivisionError
and pass the 0
through. (Be careful though. It will also catch and rescue any other error happening inside your rating_score
and ratings
calls)
Another season, another reason, to love Ruby :)
You have to initialize this value before use, for example like this:
def do_foobar
self.rating |= 1
self.rating = (rating_score/rating)
end
What about:
rating = rating_score/ratings if ratings != 0
精彩评论