我一直在這掙了幾天。我有這樣的模式:工廠女孩:創建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
一切都會通過很好,但我覺得我不應該這樣做。
是否有可能我正在測試這個錯誤,或者是在模型中構建兒童的不好做法。
任何想法將是一個很大的幫助。
非常感謝你幫我解決這個問題,我現在發現,爲什麼我們需要編寫測試。 –