has_and_belongs_to_many, avoiding dupes in the join table

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

    Just add a check in your controller before adding the record. If it does, do nothing, if it doesn't, add a new one:

    u = current_user
    a = @article
    if u.articles.exists?(a)
    
    else
      u.articles << a
    end
    

    More: "4.4.1.14 collection.exists?(...)" http://edgeguides.rubyonrails.org/association_basics.html#scopes-for-has-and-belongs-to-many

提交回复
热议问题