簡體   English   中英

工廠女孩:創建忽略accepts_nested_attributes_for上的reject_if

[英]Factory-Girl :create ignores reject_if on accepts_nested_attributes_for

我已經為此奮斗了幾天。 我有這個模型:

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

一切都會好起來的,但是我覺得我不需要這樣做。

我是否有可能測試這個錯誤,還是在模型中構建子代是錯誤的做法。

任何想法都會有很大幫助。

在模型中建立子代是不好的做法

不一定,但是我要避免after_initialize —它在模型的每個實例上執行,即使是直接find

我認為最好隔離需要添加business_location的情況,並明確地進行操作。 看來您的business_entity_with_locations工廠正是這樣做的,所以我不確定您為什么需要回調。

至於為什么accepts_nested_attributes_for無法正常工作,我相信這是因為您沒有使用它。 它期望像下面這樣的屬性哈希:

{:business_locations => {0 => {:name =>“樣本名稱}}}

傳遞給像new這樣的方法。 這不是您要執行的操作,而是在不帶任何參數的情況下在關聯上調用build 因此,永遠不會調用accepts_nested_attributes_for提供的屬性設置器邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM