2013-01-16 42 views
0

我有模型奇怪的ActiveRecord模型行为

class Owner < ActiveRecord::Base 
    attr_accessible :telephone 
    validates_uniqueness_of :telephone 
    validates_telephone_number_of :telephone 
    before_validation :telephone_normalize 
end 

在轨控制台

a = Owner.new(:telephone => '949123456') 
=> #<Owner id: nil, telephone: "949123456", created_at: nil, updated_at: nil> 
1.9.3-p362 :002 > a.valid? 
Owner Exists (0.1ms) SELECT 1 AS one FROM "owners" WHERE "owners"."telephone" = '+421949123456' LIMIT 1 
=> false 
1.9.3-p362 :003 > a 
=> #<Owner id: nil, telephone: "421949123456", created_at: nil, updated_at: nil> 

同样的,当我保存独有的编号:

1.9.3-p362 :006 > a.telephone = '949123457' 
=> "949123457" 
1.9.3-p362 :007 > a.save 
(0.1ms) begin transaction 
Owner Exists (0.2ms) SELECT 1 AS one FROM "owners" WHERE "owners"."telephone" = '+421949123457' LIMIT 1 
SQL (2.3ms) INSERT INTO "owners" ("created_at", "telephone", "updated_at") VALUES (?, ?, ?) [["created_at", Wed, 16 Jan 2013 11:55:44 UTC +00:00], ["telephone", "421949123457"], ["updated_at", Wed, 16 Jan 2013 11:55:44 UTC +00:00]] 
(88.3ms) commit transaction 
=> true 

铁轨(3.2.11)省略数字开头的'+'。数字的类型是字符串。它也保存它没有加号(如果它是唯一的),但是在验证时,它用加号呼叫。

我在做什么错?

回答

0

不幸的是我的validates_telephone_number_of验证器中有bug。它已修改的属性: -/

> a = 'aaa' # => 'aaa' 
> b = a.to_s # => 'aaa' 
> b << 'c' # => 'aaac' 
> b # => 'aaac' 
> a # => 'aaac' 

使用b = a.to_s.dup这是必要的。

1

它认为电话数据库中的列是整数类型。所以你通过的字符串超出了范围。这就是为什么你面对这个问题。