Ruby on rails 3.2 如何获得质量分配以利用自定义分配方法

Ruby on rails 3.2 如何获得质量分配以利用自定义分配方法,ruby-on-rails-3.2,rails-activerecord,Ruby On Rails 3.2,Rails Activerecord,这简直让我发疯。我有一个电话号码字段的自定义setter和自定义getter: 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

这简直让我发疯。我有一个电话号码字段的自定义setter和自定义getter:

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
但是,当我执行诸如
person.update_attributes(:phone=>'(888)123.4567')
之类的大规模赋值时,该属性直接设置,绕过我的自定义setter方法,然后验证失败,因为它不是原始形式


有什么想法吗?

不幸的是,似乎没有什么解决办法。我最终放弃了它,只是将代码复制到一个before_save过滤器中。似乎令人发指,但这就是生活

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