I'm new to Ruby on Rails. I have the following model:
class Logo < ApplicationRecord
validates :name, presence: true, length: { maximum: 255 }
validates :price, presence: true,
numericality: { greater_than_or_equal_to: 0 }
validates :stitch_count, presence: true,
numericality: { greater_than: 0, only_integer: true }
end
Every logo has a price. I want to validate the scale of the price. It must accept the following:
[10.44, 12.1, 16] and reject the following: [10.123, 13.11111, 16.123], as these are obviously not valid prices. I've tried validating by format using the following regex: /\A\d+(?:\.\d{0,2})?\z/
, which, according to another poster on Stack Overflow, validates for at most 2 decimal places. It doesn't work. Another poster on Stack Overflow pointed out that the number of decimal places only matters when the value is a string, and that by the time the validator runs, it's no longer a string. His suggestions, as well as a few more, don't work. So how would I run a regex on a decimal? You would think Rails would have something to validate if a number is a valid price or not.
I run the following test:
def setup
@logo = Logo.new(name: "ASG Security", price: 12, stitch_count: 15000, note: "Ali")
end
test "price scale must be less than 2" do
@logo.price = 14.995
assert_not @logo.valid?
end