has_and_belongs_to_many, avoiding dupes in the join table

前端 未结 12 955
南旧
南旧 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条回答
  •  萌比男神i
    2020-12-04 11:55

    In Rails4:

    class Post < ActiveRecord::Base 
      has_and_belongs_to_many :tags, -> { uniq }
    

    (beware, the -> { uniq } must be directly after the relation name, before other params)

    Rails documentation

提交回复
热议问题