Convert User input to integer

后端 未结 3 1339
难免孤独
难免孤独 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:10

    One way is to override the mechanism on the model that sets the price, like this:

    def price=(val)
        write_attribute :price, val.to_s.gsub(/\D/, '').to_i
    end
    

    So when you do @model.price = whatever, it will go to this method instead of the rails default attribute writer. Then you can convert the number and use write_attribute to do the actual writing (you have to do it this way because the standard price= is now this method!).

    I like this method best, but for reference another way to do it is in your controller before assigning it to the model. The parameter comes in as a string, but the model is converting that string to a number, so work with the parameter directly. Something like this (just adapt it to your controller code):

    def create
        @model = Model.new(params[:model])
        @model.price = params[:model][:price].gsub(/\D/, '').to_i
        @model.save
    end
    

    For either solution, remove that before_validation.

提交回复
热议问题