2010-03-18 28 views
7

我有這樣我使用的是序列工廠女孩獲得獨特的價值觀,但我得到驗證錯誤

class Lga < ActiveRecord::Base 
    validates_uniqueness_of :code 
    validates_presence_of :name 
end 

我定義爲L氣體工廠與

Factory.sequence(:lga_id) { |n| n + 10000 } 

Factory.define :lga do |l| 
    id = Factory.next :lga_id 
    l.code "lga_#{id}" 
    l.name "LGA #{id}" 
end 
定義的模型

然而,當我在script/console運行

Factory.create(:lga) 
Factory.create(:lga) 

我得到

>> Factory.create(:lga) 
=> #<Lga id: 2, code: "lga_10001", name: "LGA 10001", created_at: "2010-03-18 23:55:29", updated_at: "2010-03-18 23:55:29"> 
>> Factory.create(:lga) 
ActiveRecord::RecordInvalid: Validation failed: Code has already been taken 

回答

7

問題是codename屬性並沒有所謂的懶屬性。我曾想過寫東西喜歡的:

Factory.define :lga do |l| 
    l.code { |n| "lga_#{n+10000}" } 
end 

,但我想重用在name屬性的ID了。您可以確保 比id每次Factory.create是通過將其在after_build鉤稱爲評估。

Factory.define :lga do |l| 
    l.after_build do |lga| 
    id = Factory.next :lga_id 
    lga.code = "lga_#{id}" 
    lga.name = "LGA #{id}" 
    end 
end 

這隻適用於FactoryGirl 1.2.3及以上版本。

+0

我想你已經離開了你的最後一個例子代碼塊調試線;) – 2011-07-22 00:57:16

+0

@Ganesh。謝謝。固定。 – 2011-07-25 06:30:27