Ruby on rails Rails float列在进行验证之前自动将字母转换为数字
我的rails项目的数据库中有一个float列,它将表单中的百分比保存为float。当用户键入字母和数字的某些组合(如“12jkawd3%”)时,在我的验证将其排除为无效(它将成为有效的浮点)之前,它将转换为浮点。我目前正在使用一种在控制器中带有正则表达式的方法来防止这种情况发生,它可以工作,但我觉得必须有一种更适合rails的方法来做到这一点。我咨询过谷歌,什么也没发现。有人能帮忙吗 这是我目前的控制器。字符串\u to \u float方法是阻止当前在输入无效数据时将其转换为float的方法Ruby on rails Rails float列在进行验证之前自动将字母转换为数字,ruby-on-rails,ruby,regex,validation,type-conversion,Ruby On Rails,Ruby,Regex,Validation,Type Conversion,我的rails项目的数据库中有一个float列,它将表单中的百分比保存为float。当用户键入字母和数字的某些组合(如“12jkawd3%”)时,在我的验证将其排除为无效(它将成为有效的浮点)之前,它将转换为浮点。我目前正在使用一种在控制器中带有正则表达式的方法来防止这种情况发生,它可以工作,但我觉得必须有一种更适合rails的方法来做到这一点。我咨询过谷歌,什么也没发现。有人能帮忙吗 这是我目前的控制器。字符串\u to \u float方法是阻止当前在输入无效数据时将其转换为float的方法
class MyProductsNotificationsController < ApplicationController
def create
my_product = MyProduct.find(params[:my_product])
discount = NumberFormatter.string_to_float(params[:my_products_notification][:discount])
@my_products_notification = MyProductsNotification.new(my_product: my_product, discount: discount)
if @my_products_notification.save
redirect_to current_user
else
redirect_to current_user, notice: 'Invalid format for discount'
end
end
end
类MyProductsNotificationsController
NumberFormatter类(注意)忽略else 0,因为它是视图的一个边缘案例
class NumberFormatter
class << self
def string_to_float(discount_string)
if discount_string =~ /(?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )/
discount_string
else
0
end
end
类编号格式
当您在变量中输入某个值时,rails基本上会根据数据库列的数据类型转换输入数据
您可以将值设置为attr\u访问器,并检查此变量的有效性,然后相应地更新旧的数据库浮点变量。将参考代码添加到您的问题确定我更新了代码。attr\u访问器将去哪里?抱歉,我对此有点陌生。您可以给我一个示例吗?attr\u访问器不存储在数据库中
class MyProductsNotification < ActiveRecord::Base
belongs_to :my_product
before_create :string_to_float
validates :discount, numericality: { greater_than: 0, less_than_or_equal_to: 100, message: 'is invalid.' }
private
def string_to_float
self.discount = '%.2f' % (self.discount || 0)
end
end
<%= form_for @my_product_notification do |f| %>
<% if product.my_products_notification %>
<% discount = product.my_products_notification.discount %>
<% else %>
<% discount = '' %>
<% end %>
<%= hidden_field_tag :my_product, product.id -%>
<%= f.label "Percentage discount threshold: %" %>
<%= f.text_field :discount, value: discount %>
<%= f.submit 'Save notification' %>
<% end -%>