2012-11-12 14 views
2

我一直在這掙了幾天。我有這樣的模式:工廠女孩:創建ignore_ifception_nested_attributes_for的拒絕_if

class BusinessEntity < ActiveRecord::Base 

    has_many :business_locations 
    accepts_nested_attributes_for :business_locations, :allow_destroy => true, 
     :reject_if => proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } } 

after_initialize :build_child 

    .... 

    def build_child 
    self.business_locations.build if self.business_locations.empty?  
    end 

business_entites.rb(廠)

FactoryGirl.define do 
    factory :business_entity do 
    name "DaveHahnDev" 
    association :company, :factory => :company 
    association :default_currency, :factory => :currency 

    factory :business_entity_with_locations do 
     after(:build) do |business_entity| 
     business_entity.class.skip_callback(:create, :after, :set_primary_business_info) 
     business_entity.business_locations << FactoryGirl.build(:business_location) 
     end 
    end 
    end 

    factory :business_location do 
    name "Main Office" 
    business_entity 
    address1 "139 fittons road west" 
    address2 "a different address" 
    city { Faker::Address.city } 
    province "Ontario" 
    country "Canada" 
    postal_code "L3V3V3" 

    end 
end 

現在,當我在一個規範調用FactoryGirl.create(:business_entity)我得到business_locations valdation錯誤有空白的屬性。這是由after_initialize回調初始化的孩子。我認爲reject_if會照顧到這一點,就像從瀏覽器使用應用程序一樣。如果我加:

before_validation :remove_blank_children 

    def remove_blank_children 
    self.business_locations.each do |bl| 
     bl.mark_for_destruction if bl.attributes.all? {|k,v| v.blank?} 
    end 
    end 

一切都會通過很好,但我覺得我不應該這樣做。

是否有可能我正在測試這個錯誤,或者是在模型中構建兒童的不好做法。

任何想法將是一個很大的幫助。

回答

1

是不好的做法,在模型中

建立兒童不一定,但我會避免after_initialize - 它是在模型的每一個實例,甚至直find執行。

我認爲你最好隔離需要添加business_location並明確執行的情況。由於您的business_entity_with_locations工廠似乎正在這樣做,我不確定爲什麼您需要回撥。

至於爲什麼accepts_nested_attributes_for不工作,我相信那是因爲你沒有使用它。該公司預計的屬性哈希,如:

{:business_locations => {0 => {:名稱=>「樣品名稱}}}

傳遞到像new的方法那是不是你在做什麼。因爲你在沒有任何參數的情況下調用了build關聯,所以accepts_nested_attributes_for提供的屬性設置器邏輯從不會被調用

+0

非常感謝你幫我解決這個問題,我現在發現,爲什麼我們需要編寫測試。 –