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

前端 未结 8 802
生来不讨喜
生来不讨喜 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:50

    Here's something simple that makes sure that number input is read correctly. The output will still be with a point instead of a comma. That's not beautiful, but at least not critical in some cases.

    It requires one method call in the controller where you want to enable the comma delimiter. Maybe not perfect in terms of MVC but pretty simple, e.g.:

    class ProductsController < ApplicationController
    
      def create
        # correct the comma separation:
        allow_comma(params[:product][:gross_price])
    
        @product = Product.new(params[:product])
    
        if @product.save
          redirect_to @product, :notice => 'Product was successfully created.'
        else
          render :action => "new"
        end
      end
    
    end
    

    The idea is to modify the parameter string, e.g.:

    class ApplicationController < ActionController::Base
    
      def allow_comma(number_string)
        number_string.sub!(".", "").sub!(",", ".")
      end
    
    end
    

提交回复
热议问题