I must be missing something basic but I keep getting validation errors:
app/model/person.rb
class Person < ActiveRecord::Base
attr_accessible :cell
before_validation :format_cell_string
validates :cell, :length => { :is => 10 }
protected
def format_cell_string
self.cell = self.cell.gsub!(/\D/, '') if self.cell != nil
end
end
In rails c
> bib = Person.new(cell: "1234567890")
> bib.save
leads to a ROLLBACK
bib.errors
=> #<ActiveModel::Errors:0x007fcb3cf978d8 @base=#<Person id: nil, created_at: nil, updated_at: nil, cell: nil>, @messages={:cell=>["is the wrong length (should be 10 characters)"]}>
Thinking that is could be a rails console or irb error, I also tried in my form to no avail. Trying bib = Person.new, bib.save and then bib.update_attributes(cell: “0123456789”) also doesn’t work in the console. Am I missing something! I’ve check the rails docs on validations and the rails api on model validations and tried many different things. Any thoughts? I was using rails 3.2.6 and just upgraded to rails 3.2.7. No change.
gsub!modifies the string in place and returnsnilif no changes were made:So in the case where the field contains only digits your code is setting the field to nil before the validation which causes it to fail. Using
gsub!on attributes is best avoided generally, as it doesn’t play well with Rails’ change tracking.should do the trick