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

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

    I was unable to implement the earlier def price=(price) virtual attribute suggestion because the method seems to call itself recursively.

    I ended up removing the comma from the attributes hash, since as you suspect ActiveRecord seems to truncate input with commas that gets slotted into DECIMAL fields.

    In my model:

    before_validation :remove_comma
    
    def remove_comma
      @attributes["current_balance"].gsub!(',', '')  # current_balance here corresponds to the text field input in the form view
    
      logger.debug "WAS COMMA REMOVED? ==> #{self.current_balance}"
    end
    

提交回复
热议问题