Decimals and commas when entering a number into a Ruby on Rails form

前端 未结 8 809
生来不讨喜
生来不讨喜 2020-12-08 16:19

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

8条回答
  •  没有蜡笔的小新
    2020-12-08 17:09

    I have written following code in my project. This solved all of my problems.

    config/initializers/decimal_with_comma.rb

    # frozen_string_literal: true
    
    module ActiveRecord
      module Type
        class Decimal
          private
    
          alias_method :cast_value_without_comma_separator, :cast_value
    
          def cast_value(value)
            value = value.gsub(',', '') if value.is_a?(::String)
            cast_value_without_comma_separator(value)
          end
        end
    
        class Float
          private
    
          alias_method :cast_value_without_comma_separator, :cast_value
    
          def cast_value(value)
            value = value.gsub(',', '') if value.is_a?(::String)
            cast_value_without_comma_separator(value)
          end
        end
    
        class Integer
          private
    
          alias_method :cast_value_without_comma_separator, :cast_value
    
          def cast_value(value)
            value = value.gsub(',', '') if value.is_a?(::String)
            cast_value_without_comma_separator(value)
          end
        end
      end
    end
    
    module ActiveModel
      module Validations
        class NumericalityValidator
          protected
    
            def parse_raw_value_as_a_number(raw_value)
              raw_value = raw_value.gsub(',', '') if raw_value.is_a?(::String)
              Kernel.Float(raw_value) if raw_value !~ /\A0[xX]/
            end
        end
      end
    end
    

提交回复
热议问题