在Ruby on Rails表单中输入数字时的小数和逗号 [英] Decimals and commas when entering a number into a Ruby on Rails form
问题描述
在表单中输入数字时,允许用户使用小数或逗号的最佳Ruby/Rails方法是什么?换句话说,我希望用户能够输入2,000.99而不会在我的数据库中获得2.00.
What's the best Ruby/Rails way to allow users to use decimals or commas when entering a number into a form? In other words, I would like the user be able to enter 2,000.99 and not get 2.00 in my database.
这是否有最佳实践?
-更新---
gsub是否可以与浮点数或bigintegers一起使用?还是当在表格中输入浮点数或整数时,rails会自动在处切断数字吗?我尝试使用self.price.gsub(,","),但得到"8:Fixnum的未定义方法'gsub'",其中8是我在表格中输入的任何数字.
Does gsub work with floats or bigintegers? Or does rails automatically cut the number off at the , when entering floats or ints into a form? I tried using self.price.gsub(",", "") but get "undefined method `gsub' for 8:Fixnum" where 8 is whatever number I entered in the form.
推荐答案
我在尝试在表单中使用本地化内容时遇到了类似的问题.使用ActionView::Helpers::NumberHelper
内置方法对输出进行本地化相对简单,但是ActiveRecord
不支持对本地化的输入进行解析.
I had a similar problem trying to use localized content inside forms. Localizing output is relatively simple using ActionView::Helpers::NumberHelper
built-in methods, but parsing localized input it is not supported by ActiveRecord
.
这是我的解决方案,请告诉我是否做错了什么.在我看来,太简单了,无法找到正确的解决方案.谢谢! :)
This is my solution, please, tell me if I'm doing anything wrong. It seems to me too simple to be the right solution. Thanks! :)
首先,让我们为String
添加一个方法.
First of all, let's add a method to String
.
class String
def to_delocalized_decimal
delimiter = I18n::t('number.format.delimiter')
separator = I18n::t('number.format.separator')
self.gsub(/[#{delimiter}#{separator}]/, delimiter => '', separator => '.')
end
end
然后让我们向ActiveRecord::Base
class ActiveRecord::Base
def self.attr_localized(*fields)
fields.each do |field|
define_method("#{field}=") do |value|
self[field] = value.is_a?(String) ? value.to_delocalized_decimal : value
end
end
end
end
最后,让我们声明哪些字段的输入应该本地化.
Finally, let's declare what fields should have an input localized.
class Article < ActiveRecord::Base
attr_localized :price
end
现在,您可以在表格中输入"1.936,27",并且ActiveRecord
不会对无效数字产生错误,因为它变为1936.27.
Now, in your form you can enter "1.936,27" and ActiveRecord
will not raise errors on invalid number, because it becomes 1936.27.
这篇关于在Ruby on Rails表单中输入数字时的小数和逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!