我已经为此苦苦挣扎了几天。我有这个模型:
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 的验证错误有空白属性。这是由 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
一切都会好起来的,但我觉得我不应该这样做。
是否有可能我正在测试这个错误,或者在模型中建立孩子是不好的做法。
任何想法都会有很大帮助。