这让我彻底疯了。我有一个电话号码字段的自定义设置器和一个自定义获取器:
class Person < ActiveRecord::Base
attr_accessible :phone
def phone=(p)
p = p.to_s.gsub(/\D+/, '')
p = p[1..-1] if p.length == 11 && p[0] == '1'
write_attribute(:phone, p)
end
def phone(format=:display)
case format
when :display then return pretty_display(attributes['phone'])
when :dialable then return dialable(attributes['phone'])
else return attributes['phone']
end
end
case 语句中的方法只是我实际实现的存根,因此无需挂断这些方法。当我直接使用对象时,这些 get 和 set 方法效果很好。例如:
person = Person.find(1)
person.phone = '(888) 123.4567'`)
puts person.phone # => 888.123.4567
puts person.phone(:dialable) # => +18881234567
puts person.phone(:raw) # => 8881234567
但是当我做一个像这样的批量赋值时person.update_attributes( :phone => '(888) 123.4567' )
,属性被直接设置,绕过我的自定义设置方法,然后验证失败,因为它不是原始形式。
有任何想法吗?