It's almost for myself, so I'll write it briefly.
You can comment on user and project.
comment.rb
belongs_to :commentable, polymorphic: true
belongs_to :commenter, class_name: 'User'
user.rb
has_many :comments, as: :commentable, dependent: :destroy
preject.rb
has_many :comments, as: :commentable, dependent: :destroy
Just write both factories
factories/comment.rb
FactoryBot.define do
factory :project_comment, class: 'Comment' do
association :commenter, factory: :user
association :commentable, factory: :project
commentable_type { 'User' }
comment { 'Sample Comment' }
end
factory :user_comment, class: 'Comment' do
association :commenter, factory: :user
association :commentable, factory: :user
commentable_type { 'User }
comment { 'Sample Comment' }
end
end
let(:user_comment) { FactoryBot.create(:user_comment) }
Can be called with.
Polymorphic related should be easy to add related models, Therefore, I think it should be easy to add a factory. If you write like this, you can increase the comment_type even if the number of related models increases in the future.
factories/comment.rb
FactoryBot.define do
comment_type = [:user, :project]
comment_type.each do |type|
factory :"#{type}_comment", class: 'Comment' do
association :commenter, factory: :user
association :commentable, factory: type
commentable_type { type.to_s.camelize }
comment { 'Sample Comment' }
end
end
end
Conversely, if increasing comment_type does not support it, it should not be polymorphic. If the method and factory configurations change depending on the related model, why not consider STI instead of polymorphic.
Recommended Posts