has_and_belongs_to_many, avoiding dupes in the join table

前端 未结 12 985
南旧
南旧 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

    To me work

    1. adding unique index on the join table
    2. override << method in the relation

      has_and_belongs_to_many :groups do
        def << (group)
          group -= self if group.respond_to?(:to_a)
          super group unless include?(group)
        end
      end
      

提交回复
热议问题