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 |
@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
Awesome!