これは私を完全に狂わせています。電話番号フィールド用のカスタム セッターとカスタム ゲッターがあります。
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' )
、カスタム セッター メソッドをバイパスして属性が直接設定され、生の形式ではないため検証が失敗します。
何か案は?