LoginSignup
0
1

More than 3 years have passed since last update.

ポリモーフィック関連付けをしたModelでのfactoryの作り方

Last updated at Posted at 2021-01-13

ほぼ自分用なので簡易的に記します。

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などを検討してみればいかがでしょうか。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1