Ruby on Rails - Iterate decimal numbers for rating field

I have a review model that allows you to use the "1-10" system for products. In my view of the form, here is how I made the field to spit out the dropdown menu 1-10 ...

<%= f.select :rating, options_for_select((0..10).to_a, @review.rating) %> 

Works great, but the team now wants to have .5 decimal numbers for the rating system, so something can be rated 7.5, 8.0, 8.5, etc.

However, this puzzled me ... how can I change the code above and iterate over a set of numbers and increment it by .5 every time in Ruby? (Note. Yes, I already converted my rating column from integer to float.)

+6
source share
2 answers

You can define the increment as such

 (0..10).step(0.5) 
+14
source

The answer marked as correct is incorrect. It suffers from floating point precision errors - you can read about this common computer science problem here: https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

To accurately increase this range, you must pass BigDecimal to the step function instead of the default Ruby float:

 require 'bigdecimal' require 'bigdecimal/util' (0..10).step(0.5.to_d) 
+3
source

Source: https://habr.com/ru/post/887023/


All Articles