thoughtbot/factory_girl — Issue #222: Troubles with belongs_to association
Author: heaven
Created: 2011-10-23 07:28:34+00:00
State: open

class Profile < ActiveRecord::Base
has_one :primary_phone, :dependent => :destroy, :class_name => 'Phone'
has_many :phones
end

class Phone < ActiveRecord::Base
belongs_to :profile
validates :profile, :presence => true
end

Factory.define :profile do |profile|
profile.primary_phone { |p| p.association(:phone, :method => :build) } #Works as expected
profile.phones {|p| [p.association(:phone, :method => :build)] } #Din't work
end

ruby-1.9.2-p290 :001 > profile = Factory.build :profile
ruby-1.9.2-p290 :002 > profile.primary_phone
=> #
ruby-1.9.2-p290 :003 > profile.phones
=> [#]
ruby-1.9.2-p290 :004 > profile.save
=> false
ruby-1.9.2-p290 :005 > profile.errors
=> #["is invalid"]}>
ruby-1.9.2-p290 :006 > profile.phones.first.errors
=> #["can't be blank"]}>

But if replace has_many :phones by has_and_belongs_to_many :phones it works fine and all the related phones are being saved correctly.