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
@happyFish
Copy link

Thank you! I've been trying to find the solution to this all morning!

@danielpuglisi
Copy link

<3

@saeedSarpas
Copy link

Thanks ^__^

@nozpheratu
Copy link

I believe the correct syntax in 4+ is now simply:

FactoryGirl.define do
  factory :alert do
    alertable { |a| a.association(:region) }
  end
end

@davestephens
Copy link

@nozpheratu Your solution works perfectly, thanks.

@anthonyms
Copy link

<3

@Petecass
Copy link

Petecass commented Nov 6, 2016

🎉

@mstashev
Copy link

mstashev commented Apr 11, 2017

But what if you have multiple polymorphic relationships? (Sorry. New-ish to Rails and Factory Girl.)

class Tag < ApplicationRecord
  has_many :taggings
  has_many :taggable, through: :taggings
  has_many :plans, through: :taggings, source: 'Plan'
  has_many :drills, through: :taggings, source: 'Drill'
end

class Plan < ApplicationRecord
  has_many :taggings, as: :taggable
  has_many :tags, through: :taggings
  has_many :drill_plans
  has_many :drills, through: :drill_plans
end

class Drill < ApplicationRecord
  has_many :drill_plans
  has_many :plans, through: :drill_plans
  has_many :taggings, as: :taggable
  has_many :tags, through: :taggings
end

class Tagging < ApplicationRecord
  belongs_to :tag
  belongs_to :taggable, polymorphic: true
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