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

前端 未结 8 763
生来不讨喜
生来不讨喜 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 16:45

    Here's some code I copied from Greg Brown (author of Ruby Best Practices) a few years back. In your model, you identify which items are "humanized".

    class LineItem < ActiveRecord::Base
      humanized_integer_accessor :quantity
      humanized_money_accessor :price
    end
    

    In your view templates, you need to reference the humanized fields:

    = form_for @line_item do |f|
      Price:
      = f.text_field :price_humanized
    

    This is driven by the following:

    class ActiveRecord::Base
      def self.humanized_integer_accessor(*fields)
        fields.each do |f|
          define_method("#{f}_humanized") do
            val = read_attribute(f)
            val ? val.to_i.with_commas : nil
          end
          define_method("#{f}_humanized=") do |e|
            write_attribute(f,e.to_s.delete(","))
          end
        end
      end
    
      def self.humanized_float_accessor(*fields)
        fields.each do |f|
          define_method("#{f}_humanized") do
            val = read_attribute(f)
            val ? val.to_f.with_commas : nil
          end
          define_method("#{f}_humanized=") do |e|
            write_attribute(f,e.to_s.delete(","))
          end
        end
      end
    
      def self.humanized_money_accessor(*fields)
        fields.each do |f|
          define_method("#{f}_humanized") do
            val = read_attribute(f)
            val ? ("$" + val.to_f.with_commas) : nil
          end
          define_method("#{f}_humanized=") do |e|
            write_attribute(f,e.to_s.delete(",$"))
          end
        end
      end
    end
    

提交回复
热议问题