rails 在保存前去除非数值 [英] rails strip non numeric values before save

查看:25
本文介绍了rails 在保存前去除非数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索过,看起来这应该很简单,但我无法让它工作.我试图在保存电话号码之前删除所有非数字字符.这是我目前拥有的:

I have searched and it looks like this should be simple but I can't get it to work. I am trying to remove all non-numeric characters prior to saving a phone number. This is what I have currently:

before_save { |workorder| workorder.phonenumber = 
                  phonenumber.to_s.gsub(/\D/, '').to_i }

所以如果用户输入

925-555-5555

它应该保存 9255555555 但它实际上只保存了 925 并且忽略了之后的所有内容

It should save 9255555555 but it is actually saving only 925 and ignoring everything after

我也试过:

before_save { |workorder| workorder.phonenumber = 
                  phonenumber.to_s.gsub(/[^0-9]/, "").to_i }

结果相同.

已解决:

def raw_phonenumber
  self.phonenumber
end
def raw_phonenumber=(s)
  self.phonenumber=s.gsub(/\D/, '')
end

推荐答案

您当然已经将 phonenumber 列定义为数字.这就是为什么当您在 phonenumber 属性中设置 '925-555-5555' 时,它会被转换为一个数字,并且只保留 925.

You certainly have defined the phonenumber column as number. That's why when you set '925-555-5555' in the phonenumber attribute, it is casted to a number, and only 925 is kept.

最好的解决方案是将数据库中列的类型更改为string.创建一个新的迁移:

The best solution is to change the type of the column in your database to string. Create a new migration:

change_column :table_name, :phonenumber, :string, limit: 30

否则,您可以像这样覆盖 setter 以删除非数字字符(但它不会修复以0"开头的电话号码):

Otherwise, you can override the setter like this to remove the non numeric characters (but it won't fix phone numbers starting with '0's):

def phonenumber=(phonenumber)
  write_attribute(:phonenumber, phonenumber.gsub(/\D/, ''))
end

博客文章中的更多替代方案

这篇关于rails 在保存前去除非数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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