has_and_belongs_to_many, avoiding dupes in the join table

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

    This is really old but I thought I'd share my way of doing this.

    class Tag < ActiveRecord::Base 
        has_and_belongs_to_many :posts
    end 
    
    class Post < ActiveRecord::Base 
        has_and_belongs_to_many :tags
    end
    

    In the code where I need to add tags to a post, I do something like:

    new_tag = Tag.find_by(name: 'cool')
    post.tag_ids = (post.tag_ids + [new_tag.id]).uniq
    

    This has the effect of automatically adding/removing tags as necessary or doing nothing if that's the case.

提交回复
热议问题