去除 Rails 中除数字以外的所有字符
Strip all characters except digits in Rails
我的用户正在提供这些输入
123 - 4567 - 5665
123124-124325
但我只需要用数字形式提交。此外,我不能指望用户通过向他们发出警报来为我做这件事。那对他们来说太不方便了。
所以在 DB 中的结果应该是这样 12345675665
我在 rails 4.2.
上使用 ruby
我应该在什么地方使用什么过滤器?
class YourModel < ActiveRecord::Base
before_validation :tweak_my_attribute
def tweak_my_attribute
self.my_attribute = my_attribute.to_s.gsub(/\D/, '')
end
end
我的用户正在提供这些输入
123 - 4567 - 5665
123124-124325
但我只需要用数字形式提交。此外,我不能指望用户通过向他们发出警报来为我做这件事。那对他们来说太不方便了。
所以在 DB 中的结果应该是这样 12345675665
我在 rails 4.2.
上使用 ruby我应该在什么地方使用什么过滤器?
class YourModel < ActiveRecord::Base
before_validation :tweak_my_attribute
def tweak_my_attribute
self.my_attribute = my_attribute.to_s.gsub(/\D/, '')
end
end