回答

3

我建議你考慮切換到使用has_many :items, :through => :link_table
它已經成爲了新的標準,這是一個偉大的方法,因爲你會得到更多的靈活性「的出爐」,結構也準備易於擴展和增長沒有重大返工,例如添加新的屬性非常簡單。 '新屬性'通常是日期字段。
因此,您可以添加常規時間戳字段(創建和更新),並且人們還可以找到像'completed_on','authorized_on','terminated_on','activated_on','sold_on'等有用的其他日期字段,這取決於應用程序用例。

class Image < ActiveRecord::Base 
    has_many :image_tags 
    has_many :tags, :through => :image_tags 
end 

class ImageTag < ActiveRecord::Base 
    belongs_to :image 
    belongs_to :tag 
end 

class Tag < ActiveRecord::Base 
    has_many :image_tags 
    has_many :images, :through => :image_tags 
end 

你仍然會看到很多HABTM的例子,它仍然有效。當然有些情況下使用它仍然有意義,但是正如HMT所做的那樣,KISS表示使用「單向」。

+2

然後,您可以像\ @ image.tags那樣獲取特定圖像的所有標籤,或者@ @ tag.images獲取與標籤關聯的所有圖像 – Faisal

+0

通過正確遷移「ImageTag」表格和產生的方法'@ image.tags'和'@ tag.images',@Zequez擁有他所需要的一切。 – mliebelt

+0

對不起,不得不這樣做\ @因爲評論系統認爲我正在鏈接堆棧溢出用戶:s ...只是在標誌前刪除退格 – Faisal

相關問題