Convert User input to integer

后端 未结 3 1355
难免孤独
难免孤独 2021-02-14 05:10

So I have a form where users can input a price. I\'m trying to make a before_validation that normalizes the data, clipping the $ if the user puts it.

before_val         


        
3条回答
  •  时光取名叫无心
    2021-02-14 06:01

    I would define a virtual attribute and do my manipulation there allowing you to format and modify both the getter and setter at will:

    class Model < ActiveRecord::Base
    
      def foo_price=(price)
        self.price = price... #=> Mods to string here
      end
    
      def foo_price
        "$#{price}"
      end
    

    You also might want to note that:

    "$50.00".gsub(/\D/, '').to_i #=> 5000
    

提交回复
热议问题