rails strip non numeric values before save
The easiest way to do it is by mutating the field=
method:
def field=(value)
super(value.delete('^0-9'))
end
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.
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
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
More alternatives in this blog post