Skip to content

Instantly share code, notes, and snippets.

@xuncheng
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuncheng/1c827d9d7bbe218959e4 to your computer and use it in GitHub Desktop.
Save xuncheng/1c827d9d7bbe218959e4 to your computer and use it in GitHub Desktop.
FactoryGirl with polymorphic associations
# 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