2013-01-16 40 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

它認爲電話數據庫中的列是整數類型。所以你通過的字符串超出了範圍。這就是爲什麼你面對這個問題。