我在我的rails项目的数据库中有一个浮点列,它将表单中的百分比作为浮点保存起来。当用户输入一些字母和数字的组合,例如“12jkawd3%”时,它会被转换为浮点数,然后我的验证可以将其排除为无效(它变成一个有效的浮点数)。我目前正在控制器中使用一个正则表达式的方法来防止这种情况发生,它的工作原理,但我觉得必须有更多的方式来做到这一点。我咨询了Google,没有发现任何东西。谁能帮忙?在我的验证可以发生之前,Rails浮动列将字母自动转换为数字
这是我目前的控制器。该string_to_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
NumberFormatter类(注忽略否则为0,因为它是东西的边缘情况的意见。
class NumberFormatter
class << self
def string_to_float(discount_string)
if discount_string =~ /(?<=^|)\d+(\.\d+)?(?=$|)|(?<=^|)\.\d+(?=$|)/
discount_string
else
0
end
end
我的模型
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 -%>
添加参考代码到您的问题 – RAJ
好我更新了代码。 –