在 Ruby on Rails 表单中输入数字时的小数和逗号 [英] Decimals and commas when entering a number into a Ruby on Rails form

查看:23
本文介绍了在 Ruby on Rails 表单中输入数字时的小数和逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

允许用户在表单中输入数字时使用小数或逗号的最佳 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 是否适用于浮点数或大整数?或者,当在表单中输入浮点数或整数时,rails 会自动切断 , 处的数字吗?我尝试使用 self.price.gsub(",", "") 但得到未定义的方法 `gsub' for 8:Fixnum",其中 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆