0

My api has Posts. Each post has a number of upvotes and downvotes. I wish to update the percentage of upvotes and downvotes each time an upvote/downvote is made.

In my VotesController I have:

#PUT /downvote/:id
def downvote
    @post = Post.find(params[:id])
    @post.downvotes = @post.downvotes + 1
    @post.recalculate_percentages()
    @post.save
    render json:@post
end

In my Post model I have a method that refreshes these values:

def recalculate_percentages
    self.downvotes_percentage = self.downvotes / (self.downvotes + self.upvotes)
    self.upvotes_percentage = self.upvotes / (self.downvotes + self.upvotes)
end

Why are these changes not having any effect. In the rendered JSON the values for the percentages remain at 0.

Luis V.F
  • 43
  • 3

1 Answers1

1

Try to_f:

votes = (self.downvotes + self.upvotes).to_f
self.downvotes_percentage = self.downvotes / votes
self.upvotes_percentage = self.upvotes / votes
Rajkaran Mishra
  • 4,532
  • 2
  • 36
  • 61
  • Worked perfectly. I'm new to Ruby, didn't know this. Will accept as correct as soon as stack overflow will let me. Thank you – Luis V.F Sep 18 '18 at 16:21
  • @LuisV.F This is not Ruby specific though. When calculating with integers you will get an [integer](http://ruby-doc.org/core-2.5.1/Integer.html) as result `3 / 2 #=> 1`. If one of the two values is a float the result will be a [float](http://ruby-doc.org/core-2.5.1/Float.html) `3.0 / 2 #=> 1.5`. If one of the two values is a rational you will get a [rational](http://ruby-doc.org/core-2.5.1/Rational.html) as result `3r / 2 #=> (3/2)`. – 3limin4t0r Sep 18 '18 at 16:30
  • @JohanWentholt this _is_ language-specific, though. For example, python 2 and 3 handle this differently. – Sergio Tulentsev Sep 18 '18 at 16:32
  • @SergioTulentsev I agree with you that it is language specific, however that's not what I'm saying. You will encounter the same behaviour in Java, C, C# and other languages. – 3limin4t0r Sep 18 '18 at 16:54