Monday, August 9, 2010

Factory Girl & Polymorphic Associations

Suppose you have a case like that

class Address < ActiveRecord::Base
  belongs_to :addressable, polymorphic => true
end

class Listing < ActiveRecord::Base
  has_one :address, as => :addressable
end

class Customer < ActiveRecord::Base
  has_one :address, as => :addressable
end

Now in your factories you will have something like that

Factory.define :listing do |f|
  f.association :address
end

since addressable is required, we choose it to be by default related to a customer unless else stated

Factory.define :address do |f|
  f.association :addressable, :factory => :customer
end

right now if you tried to use the Listing Factory, you will get an address associated with dummy customer and no effect on your side

How can this be fixed ?

Factory.define :listing do |f|
  f.after_build do |listing|
    listing.address = Factory.create(:address, :addressable => listing)
  end
end

This was the only solution i found after searching for a while
which is a good solution and doesn't need a lot of work to be done

3 comments:

Santuxus said...

Short, nice and simple solution. I was looking for it for some time and finally found it here. Thank you for that post!

Nicholas Pufal said...

This is an awesome post.

I wish it was more popular.

I have been having many issues using polymorphic associations (in my case they are has_many) and your post showed the path to go.

Thanks for this.

Donkey Kong said...

Nice. Thanks for the post!