ほぼ自分用なので簡易的に記します。
userと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
両方のfactoryを書いてあげれば良い
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) }
で呼び出せる。
ポリモーフィック関連は関連するモデルの追加が簡単であるべき、
よってfactoryの追加も簡単であるべきだと思う。
このように書けば、今後関連モデルが増えてもcomment_typeを増やして対応できる。
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
逆にcomment_typeを増やしても対応できない場合は、ポリモーフィックにすべきではない。
関連モデルによってメソッドやfactoryの構成が変わるようでしたらポリモーフィックではなく,STIなどを検討してみればいかがでしょうか。