Rails:Validates_format_of for float无法正常工作

Kri*_*mar 5 format floating-point validation ruby-on-rails

我是Ruby on Rails的新手.我试图验证其中一个属性的格式只输入float.

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

但是当我只在价格中输入字符时,它接受它并显示价格的0.0值.任何人都可以告诉,这有什么问题或者为什么会这样?

pet*_*bal 11

这是我的解决方案,

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

当您填写示例7时,它会自动将值传输到7.0


mbi*_*ard 0

浮点数是数字,正则表达式是字符串。

看起来,当您输入浮点数的字符串时,Rails 会自动将其转换为 0.0。

该列上有默认值 (0.0) 吗?如果是,那么您可以尝试将其删除并validates_presence_of :price仅使用。


可以尝试的事情:不要将字符串直接放入列中price,而是将其放入price_stringattr 中并使用before_save回调尝试将字符串转换为价格。像这样的东西:

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
Run Code Online (Sandbox Code Playgroud)

在您的表单中,将 text_field 的名称更改为:price_string