Problem with Factory_girl, association and after_initialize

前端 未结 3 1657
予麋鹿
予麋鹿 2021-02-07 02:12

I have a Family class so defined:

class Family < ActiveRecord::Base
  after_initialize :initialize_family
  belongs_to :user
  validates :user, 
       :prese         


        
3条回答
  •  無奈伤痛
    2021-02-07 02:34

    Since after_initialize is triggered after new objects are instantiated and factory_girl builds instances by calling new without any arguments by default, you must use initialize_with to overwrite the default build.

    FactoryGirl.define do
      factory :family do
        initialize_with { new(user: build(:user)) }
      end
    end
    

提交回复
热议问题