Last active
August 29, 2015 14:18
-
-
Save xuncheng/1c827d9d7bbe218959e4 to your computer and use it in GitHub Desktop.
FactoryGirl with polymorphic associations
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
# a common polymorphic model | |
class Comment < ActiveRecord::Base | |
belongs_to :commentable, polymorphic: true | |
end | |
class Article < ActiveRecord::Base | |
has_many :comments, as: :commentable, dependent: :destroy | |
end | |
class Collection < ActiveRecord::Base | |
has_many :comments, as: :commentable, dependent: :destroy | |
end | |
# this is how you can build your factories in FactoryGirl | |
# to deal with the polymorphic association | |
FactoryGirl.define do | |
factory :article_comment, class: "Comment" do | |
association :commentable, factory: :article | |
# other attributes for slideshow model | |
end | |
factory :collection_comment, class: "Comment" do | |
association :commentable, factory: :collection | |
# other attributes for article model | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment