Created
May 29, 2012 20:33
-
-
Save traviskroberts/2830535 to your computer and use it in GitHub Desktop.
FactoryGirl Polymorphic Association
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
<3
Thanks ^__^
I believe the correct syntax in 4+ is now simply:
FactoryGirl.define do
factory :alert do
alertable { |a| a.association(:region) }
end
end
@nozpheratu Your solution works perfectly, thanks.
<3
🎉
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
Awesome!
@mstashev For multiple polymorphic relationships, you refer this link:
http://markcharlesdesign.blogspot.jp/2013/06/factorygirl-with-polymorphic.html
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
Thank you! I've been trying to find the solution to this all morning!