title: How to force FactoryGirl to create parent before creating factory?
body: <p>I have an Event model that, when saved, updates some attributes on the parent User.</p>
  
  <pre><code>class User
    has_many :events
  end
  
  class Event
    belongs_to :user
    before_save :update_user_attributes
  
    validates :user, presence: true
  
    def update_user_attributes
      self.user.update_attributes(hash_of_params)
    end
  end
  </code></pre>
  
  <p>This works fine most of the time — a User must exist and be logged in before they can interact with an Event. </p>
  
  <p>But my test suite is causing problems, specifically the event factory.</p>
  
  <pre><code>FactoryGirl.define do
    factory :event do
      user
    end
  end
  </code></pre>
  
  <p>It seems that, due to the order FactoryGirl builds the Event, the User is not available at the time the Event is created, causing <code>update_user_attributes</code> to fail. </p>
  
  <p>This means that </p>
  
  <pre><code>create(:event)
  # ActiveRecord::RecordNotSaved:
  # Failed to save the record
  </code></pre>
  
  <p>but </p>
  
  <pre><code>build(:event).save
  </code></pre>
  
  <p>passes without errors </p>
  
  <p>There are a number of ways I could prevent the error being raised, e.g., check that <code>user.persisted?</code> in the <code>update_user_attributes</code> method, or run the callaback <code>after_save</code>. But my question specifically relates to FactoryGirl. </p>
  
  <p>Given the above factoy, is there a way to force the associated User to be created before creating the Event?</p>