has_and_belongs_to_many, avoiding dupes in the join table

前端 未结 12 793
南旧
南旧 2020-12-04 11:07

I have a pretty simple HABTM set of models

class Tag < ActiveRecord::Base 
   has_and_belongs_to_many :posts
end 

class Post < ActiveRecord::Base 
           


        
12条回答
  •  有刺的猬
    2020-12-04 11:41

    In addition the suggestions above:

    1. add :uniq to the has_and_belongs_to_many association
    2. adding unique index on the join table

    I would do an explicit check to determine if the relationship already exists. For instance:

    post = Post.find(1)
    tag = Tag.find(2)
    post.tags << tag unless post.tags.include?(tag)
    

提交回复
热议问题