2012-11-18 37 views
1

高個子。這不是我認爲應該這樣做的方式,這意味着我做錯了;Rails HABTM協會不清除使用.clear,想法?

class Tag < ActiveRecord::Base 
    has_and_belongs_to_many :properties 
end 

class Property < ActiveRecord::Base 
    has_and_belongs_to_many :tags 

    def amenities 
    tags.where(:classification => :amenity) 
    end 
end 

所以我有屬性和標籤。他們與數據透視表具有HABTM關係。

當我在屬性上執行.tags時,我得到完整列表,如果我在該完整列表上執行.clear,它會正確地從數據庫中刪除關聯。

當我做了.amenities我得到的只是那些與設施的分類正確標記的標籤,但如果我做了.clear它不能刪除那些結果而只是再次做了.amenities查詢在控制檯輸出爲[]

所以這意味着它只是.clear'結果數組..而不是我真正想要的關聯。

所以現在的問題是; .clear來自HABTM關係的關聯的正確方法是什麼,同時給它一個where子句以限制哪些關聯被刪除?

謝謝你們。希望這不是太混亂..

+0

'.clear'是爲集合關聯創建的方法:'collection.clear',所以我認爲你不能用你自己的方法來使用它。也許你可以使用'destroy_all'方法,例如:'@ property.tags.amenities.destroy_all' – Thanh

+0

'.destroy_all'實際上「銷燬」標籤,而不僅僅是刪除關聯。我需要關聯銷燬,而不是標籤。儘管關閉! –

+0

另外'.delete_all'試圖從標籤表中刪除。 –

回答

2

而不是定義查詢標籤的方法,你可以添加另一個標記關聯的條件,如:

class Property < ActiveRecord::Base 
    has_and_belongs_to_many :tags 

    # this will be just like the tags association, except narrow the results 
    # to only tags with the classification of 'amenity' 
    has_and_belongs_to_many :amenities, 
          :class_name => 'Tag', 
          :conditions => { :classification => 'amenity' } 

end 

clear,和任何其他的habtm ASSOCATION方法,應該工作如預期。

+0

謝謝!我知道有一種方法可以做到這一點.. –

+0

不客氣,很高興幫助 – numbers1311407