Rails: Validates_format_of for float not working

I am new to Ruby on Rails. I tried to check the format of one of the attributes to only enter a float.

validates :price, :format => { :with => /^[0-9]{1,5}((\.[0-9]{1,5})?)$/, :message => "should be float" } 

but when I enter only the symbol in the price, it takes it and shows the value 0.0 for the price. can anyone say what is wrong with this or why is this happening?

+4
source share
3 answers

A float is a number, and regular expressions are for strings.

It looks like when you enter a string for float, it will automatically convert to 0.0 automatically using Rails.

Do you have a default value (0.0) in a column? If so, then you can try to remove it and use only validates_presence_of :price .


Something to try: instead of putting the row directly in the price column, put it in price_string attr and use the before_save to try to convert the row to price. Something like that:

 attr_accessor :price_string before_save :convert_price_string protected def convert_price_string if price_string begin self.price = Kernel.Float(price_string) rescue ArgumentError, TypeError errors.add(ActiveRecord::Errors.default_error_messages[:not_a_number]) end end 

And in your form, change the name of the text field to :price_string .

0
source

This is my decision,

validates :price,presence:true, numericality: {only_float: true}

when you fill, for example, 7, it automatically transfers the value to 7.0

+8
source

For rails 3:

 validates :price, :format => { :with => /^\d+??(?:\.\d{0,2})?$/ }, :numericality =>{:greater_than => 0} 
+3
source

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


All Articles