Convert User input to integer

后端 未结 3 1341
难免孤独
难免孤独 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 05:51

    My soluction colum price type decimal

    t.decimal :price, precision: 12, scale: 6
    
    # app/concern/sanitize_fields.rb
        module SanitizeFields
          extend ActiveSupport::Concern
    
          def clear_decimal(field)
            return (field.to_s.gsub(/[^\d]/, '').to_d / 100.to_d) unless field.blank?
    
          end
    
          def clear_integer(field)
            field.to_s.strip.gsub(/[^\d]/, '') unless field.blank?
          end
    
          # module ClassMethods
          #   def filter(filtering_params)
          #     results = self.where(nil)
          #     filtering_params.each do |key, value|
          #       results = results.public_send(key, value) if value.present?
          #     end
          #     results
          #   end
          #
          #   #use
          #   #def index
          #   #  @products = Product.filter(params.slice(:status, :location, :starts_with))
          #   #end
          #
          # end
    
        end
    
    #app/controllers/products_controller.rb
    
    include SanitizeFields
    
    params[:product][:price] = clear_decimal(params[:product][:price])
    

提交回复
热议问题