Lucas Luan de Melo
Lucas Luan de Melo

Reputation: 152

How to accept exact float values

I currently developing a evaluation class. This class have 4 topic fields. Eg: Technique and will accept only a range of values:

(1, 1.5, 2, 2.5, 3.0, 3.5, ... 5)

There's a way to create a validation where only will accept this values, besides see if the attribute value is on a array?

def some_name
 a_values = [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]
 !a_values.includes?(self.technique)
end

Upvotes: 0

Views: 87

Answers (1)

arieljuod
arieljuod

Reputation: 15838

You could set an inclusion validation and use a ruby range with steps to make the array of values less hardcoded https://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of

validates_inclusion_of :technique, in: (1..5).step(0.5)

Upvotes: 3

Related Questions