Dylan Richards
Dylan Richards

Reputation: 708

ZeroDivisionError - acts_as_votable

I am using acts_as_votable for upvotes and downvotes. Now I am trying to show an 'approval rating', calculated by upvotes / total votes.

The problem is there are some resources in the database with 0 total votes, hence the ZeroDivisionError. How do I fix this?

In the view:

<td><%= "#{guide.upvotes.count/guide.votes.count}" %></td>

In the controller:

  def upvote
    @guide = Guide.find(params[:id])
    @guide.liked_by current_user
    redirect_to :back
  end

  def downvote
    @guide = Guide.find(params[:id])
    @guide.downvote_from current_user
    redirect_to :back
  end

Upvotes: 0

Views: 243

Answers (1)

PinnyM
PinnyM

Reputation: 35533

You can test for a non-zero denominator. You can do this in your view:

<td><%= "#{guide.upvotes.count/guide.votes.count}" if guide.votes.count > 0 %></td>

Or, better, you can have a helper_method that does this for you:

def rating(guide)
  guide.votes.count > 0 ? (guide.upvotes.count / guide.votes.count) : 0
end

And call that in your view:

<td><%= rating(guide) %></td>

Or, even better, add it to your Guide model:

def rating
  votes.count > 0 ? (upvotes.count / votes.count) : 0
end

And in your view...

<td><%= guide.rating %></td>

Upvotes: 2

Related Questions