Skip to content

Instantly share code, notes, and snippets.

@traviskroberts
Created May 29, 2012 20:33
Show Gist options
  • Save traviskroberts/2830535 to your computer and use it in GitHub Desktop.
Save traviskroberts/2830535 to your computer and use it in GitHub Desktop.
FactoryGirl Polymorphic Association
class Alert < ActiveRecord::Base
belongs_to :alertable, :polymorphic => true
end
class Region < ActiveRecord::Base
has_many :alerts, :as => :alertable
end
FactoryGirl.define do
Factory.define :alert do |alert|
alert.alertable { |a| a.association(:region) }
end
end
@calrrox
Copy link

calrrox commented Aug 22, 2017

Awesome!

@yangjindong
Copy link

@mstashev For multiple polymorphic relationships, you refer this link:
http://markcharlesdesign.blogspot.jp/2013/06/factorygirl-with-polymorphic.html

@TorvaldsDB
Copy link

TorvaldsDB commented Dec 21, 2018

There is the fix form factory_bot documents

Polymorphic associations can be handled with traits:

FactoryBot.define do
  factory :video
  factory :photo

  factory :comment do
    for_photo

    trait :for_video do
      association(:commentable, factory: :video)
    end

    trait :for_photo do
      association(:commentable, factory: :photo)
    end
  end
end

This allows us to do:

create(:comment)
create(:comment, :for_video)
create(:comment, :for_photo)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment