允许在数字字段中使用逗号 [英] Allowing commas in a numerical field
问题描述
这是一个如此愚蠢的问题,我觉得我一定错过了一些简单的东西.我有一个带有 quantity
字段的表单.人们在输入数量时不断输入逗号(例如,他们输入 12,000
表示一万二千),所以我想在保存数量之前去掉逗号(12000
在示例中)转换为数据库中的整数列.
This is such a dumb question that I feel like I must be missing something simple. I have a form with a quantity
field. People keep typing commas when they enter the quantity (for example, they type 12,000
to indicate twelve thousand) so I would like to strip out the commas before saving the quantity (12000
in the example) into an integer column in the database.
到目前为止我已经尝试了两种方法.按照在这个SO问题
So far I have tried two methods. Overriding the setter method as suggested in this SO question
def quantity=(num)
num.gsub!(',', '') if num.is_a?(String)
self[:quantity] = num.to_i
end
这在某种意义上是有效的.如果我在数量字段中输入 12,000
并提交表单,我会在数据库中得到 12000
.问题是它还绕过了所有 quantity
验证.例如,我不再可以验证数量值的存在.这不好.
This works in a sense. If I type 12,000
in the quantity field and submit the form, I get 12000
in the database. The problem is that it also bypasses all quantity
validations. No longer can I validate the presence of a value for quantity for example. This is not good.
我也尝试过使用 before 验证回调(而不是覆盖 setter):
I have also tried to use a before validation callback (instead of overriding the setter):
before_validation :sanitize_quantity
def sanitize_quantity
# Doesn't wok because quantity.to_i already called by this point.
end
这不起作用,因为当数量达到回调方法时,Rails 已经在其上调用了 to_i
.这意味着 12,000
将在到达回调时被截断为 12
.再一次,不好.
This doesn't work because by the time the quantity has reached the callback method, Rails has already called to_i
on it. This means that 12,000
will be truncated to 12
by the time it reaches the callback. Once again, not good.
除了在客户端去除逗号之外,我还能尝试什么?
What else can I try aside from stripping the commas on the client-side?
最后一点,我知道这实际上是一件愚蠢的事情,因为某些国家/地区以不同的方式使用句点和逗号.无论如何,我仍然需要这样做.
As a final note, I am aware that this is essentially a dumb thing to do because certain countries use periods and commas in different ways. I still need to do it anyway.
推荐答案
我实际上在阅读我的问题时发现了这一点.
I actually figured this out just as I was reading over my question.
关键是使用虚拟属性.
class Job < ActiveRecord::Base
def flexible_quantity
quantity
end
def flexible_quantity=(quantity)
self.quantity = quantity.gsub(',', '') unless quantity.blank?
end
end
然后在表单中,使用虚拟属性.
Then in the form, use the virtual attribute.
<%= f.text_field :flexible_quantity %>
现在验证 flexible_quantity 值是否存在.
Now validate the presence of the flexible_quantity value instead.
class Job < ActiveRecord::Base
validates :flexible_quantity, presence: true
# The cool this is that we can leave the numericality validation on the quantity field.
validates :quantity, presence: true, numericality: { only_integer: true }
end
这篇关于允许在数字字段中使用逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!