ruby on rails - How to validate against the object "in memory" versus the stored object in the database -
the following code works fine on creating "channels" have address emails or phones.
class channel < activerecord::base belongs_to :contact belongs_to :mechanism validates_uniqueness_of :address validates_format_of :address, :with => /@/i, :if => :address_is_email? validates_format_of :address, :with => /\d\d\d\d\d\d\d\d\d\d/, :if => :address_is_phone? def before_validation self.address = address.gsub(/[^0-9]/, "") if mechanism.designation == "sms" end def address_is_email? mechanism.designation == "smtp" end def address_is_phone? mechanism.designation == "sms" end end like so:
>> c = channel.create(:mechanism_id => 1, :address => 'something@someplace.com') => #<channel id: 17, created_at: "2010-12-02 15:00:59", updated_at: "2010-12-02 15:00:59", mechanism_id: 1, contact_id: nil, address: "something@someplace.com", enabled: nil, time_window_id: nil> >> c.save => true however, if try change format 1 other after fact, fail.
>> c.update_attributes(:address => '888.555.1212', :mechanism_id => 2) => false >> c.save => false i'm guessing because validates_format_of going through address_is_*? function, , reading against format that's stored in database (or in memory already), , not against value i'm feeding it. how test against new value i'm passing (somehow) class when try update_attributes? thing can see do, given code above, delete channel , create new 1 different format.
your problem line:
validates_format_of :address, :with => /\d\d\d\d\d\d\d\d\d\d/, :if => :address_is_phone? the regular expression expecting 10 digits, nothing in between! if want dots, example above, this:
validates_format_of :address, :with => /\d\d\d\.\d\d\d\.\d\d\d\d/, :if => :address_is_phone? and of course, can complex want there. hope helps!
ps: shorter, easier read version:
validates_format_of :address, :with => /\d{3}\.\d{3}\.\d{4}/, :if => :address_is_phone?
Comments
Post a Comment