has_and_belongs_to_many, avoiding dupes in the join table

前端 未结 12 794
南旧
南旧 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:46

    Extract the tag name for security. Check whether or not the tag exists in your tags table, then create it if it doesn't:

    name = params[:tag][:name]
    @new_tag = Tag.where(name: name).first_or_create
    

    Then check whether it exists within this specific collection, and push it if it doesn't:

    @taggable.tags << @new_tag unless @taggable.tags.exists?(@new_tag)
    

提交回复
热议问题