title: How do you create RoR Factory associations with accepts_nested_attributes_for?
body: <p>As Anton points out (thanks Anton!) my problem is Association Caching in the tests and it seems like I did correctly create the nested_attribute in the Factory.  The correct syntax is:</p>
  
  <pre><code>Factory.define :job do |f|
    ...
    f.vehicles_attributes [{:vin =&gt; "1", :model =&gt; "ford", :make =&gt; "escort"},{:vin =&gt; "1", :model =&gt; "ford", :make =&gt; "escort" }]
  end
  </code></pre>
  
  <hr>
  
  <p>I am using <code>accepts_nested__attributes_for</code> in my Job model and am trying to migrate to factory girl after nearly losing my marbles "fixture diving" every time I change the model.  </p>
  
  <p>I posted a bunch of code below but my question is straightforward:</p>
  
  <p><strong>How do I use factories to create nested_attributes?</strong>  </p>
  
  <p>I am able to create a Job instance using the code below but I cannot create create vehicles in my unit tests.  Without the <code>f.vehicles_attributes...</code> my Job tests fail validations.</p>
  
  <p>My unit tests produce the following results:</p>
  
  <pre><code>  test "factory" do
      job = Factory(:job)
      assert(job.valid?)  # =&gt; true
      assert(job.vehicles.first.valid?) # =&gt; true
      vehicle = Factory(:vehicle)
      assert(vehicle.job.vehicles.size == 1) # =&gt; true
      assert_equal(vehicle.job.vehicles.first.vin, "2") # =&gt; FALSE.  &lt;"1"&gt; expected but was &lt;"2"&gt;
    end
  </code></pre>
  
  <hr>
  
  <pre><code>Factory.define :job do |f|
    ...
    f.vehicles_attributes [:vin =&gt; "1", :model =&gt; "ford", :make =&gt; "escort" ]
  end
  
  Factory.define :vehicle do |f|
    f.vin "2"
    f.model "ford"
    f.make "escort"
    f.association :job
  end
  </code></pre>
  
  <hr>
  
  <pre><code>class Job &lt; ActiveRecord::Base
    has_many :vehicles, :dependent =&gt; :destroy
    validate :job_must_have_at_least_one_vehicle
    accepts_nested_attributes_for :vehicles, :allow_destroy =&gt; :true, :reject_if =&gt; proc { |vehicle_attributes| Job.insufficient_vehicle_input?(vehicle_attributes) }
  
    def job_must_have_at_least_one_vehicle
      errors.add(:vehicles, "need to be added") if self.vehicles.empty?
    end
  
    def self.insufficient_vehicle_input?(vehicle_attributes)
      vehicle_property_keys = vehicle_attributes.keys
      vehicle_property_keys.delete('_delete')
      vehicle_property_keys.delete('is_operational')
      vehicle_property_keys.delete('has_keys')
      vehicle_property_keys.each do |attribute_to_validate|
        if(!vehicle_attributes[attribute_to_validate].nil? &amp;&amp; !vehicle_attributes[attribute_to_validate].empty?)
          return false
        end
      end
      return true
    end
  end
  </code></pre>