2012-11-04 96 views
38

這可能是我的一個非常基本的疏忽,但我似乎無法想起一個簡單的方法來刪除通過has_many :through加入的兩個對象之間的關聯。 IE:Active Record has_many:通過刪除一個關聯的記錄

class Photo 
    has_many :tags, :through => :taggings 
    has_many :taggings, :dependent => :destroy 
end 

class Tags 
    has_many :photos, :through => :taggings 
    has_many :taggings, :dependent => :destroy 
end 

class Taggings 
    belongs_to :photo 
    belongs_to :tag 
end 

如果你有兩個對象,tagphoto,你可以將它們只是做這個關聯:

photo.tags << tag 

那麼,有沒有一個同樣簡單與此相反?即:

photo.tags.remove tag 

回答

56

這裏有你想要什麼:

photo.tags.delete(tag) 
+23

注意,這不會觸發'before_destroy'或'在連接模型after_destroy'回調 - 到位delete'的'如果使用'destroy'你需要這個。 – PinnyM

相關問題