将用户输入转换为整数 [英] Convert User input to integer

查看:55
本文介绍了将用户输入转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个用户可以输入价格的表单.我正在尝试制作一个 before_validation 来规范化数据,如果用户放置它,则剪裁 $ .

before_validation 做除非 self.price.blank?然后 self.price= self.price.to_s.gsub(/\D/, '').to_i end结尾

如果用户输入 $50 这段代码给我 0.如果用户输入 50$ 这段代码给我 50.我认为因为数据类型是整数,所以 rails 在我的 before_validation 之前运行 .to_i 并剪裁 $ 之后的所有内容.如果数据类型是字符串,同样的代码也能正常工作.

任何人都有让我保留整数数据类型的解决方案?

解决方案

一种方法是覆盖模型上设置价格的机制,如下所示:

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

所以当你做 @model.price = what 时,它会转到这个方法而不是 rails 默认属性 writer.然后你可以转换数字并使用write_attribute来做实际的写入(你必须这样做,因为标准的price=现在是这种方法!).>

我最喜欢这种方法,但作为参考,另一种方法是在将其分配给模型之前在控制器中进行.参数以字符串形式出现,但模型正在将该字符串转换为数字,因此直接使用该参数.像这样(只需将其调整为您的控制器代码):

def 创建@model = Model.new(params[:model])@model.price = params[:model][:price].gsub(/\D/, '').to_i@model.save结尾

对于任一解决方案,删除 before_validation.

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_validation do
 unless self.price.blank? then self.price= self.price.to_s.gsub(/\D/, '').to_i end
end

If user inputs $50 This code is giving me 0. If user inputs 50$ this code gives me 50. I think since the data type is integer that rails is running .to_i prior to my before_validation and clipping everything after the $. This same code works fine if the data type is a string.

Anyone have a solution that will let me keep the integer datatype?

解决方案

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.

这篇关于将用户输入转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆