0

我有標記兩個表,這樣我可以附加標籤的任何車型,它的工作原理很喜歡這麼多的多態性標記......Rails的 - 有工作不正常

有標記物品加入具有TAG_ID列,然後表另外兩列多態性taggable_type和taggable_id ...

class TaggedItem < ActiveRecord::Base 
    attr_accessible :taggable_id, :taggable_type, :tag_id 

    belongs_to :taggable, :polymorphic => true 
    belongs_to :tag 
end 

還有所有的,可以有標籤的東西,例如這裏的產品和形象模型標籤附:

class Product < ActiveRecord::Base 
    has_many :tagged_items, :as => :taggable, :dependent => :destroy 
    has_many :tags, :through => :tagged_items 
end 

class Image < ActiveRecord::Base 
    has_many :tagged_items, :as => :taggable, :dependent => :destroy 
    has_many :tags, :through => :tagged_items 
end 

問題是與標籤模式,我似乎可以得到相反的工作,在標籤上MODLE我想有一個的has_many圖像和的has_many產品,像這樣:

class Tag < ActiveRecord::Base 
    has_many :tagged_items, :dependent => :destroy 
    has_many :products, :through => :tagged_items 
    has_many :images, :through => :tagged_items 
end 

這導致一個錯誤,我想知道我該如何解決這個問題。所以標籤表通過多態標籤項目表工作。

任何幫助將不勝感激。謝謝!

編輯:

Could not find the source association(s) :product or :products in model TaggedItem. Try 'has_many :products, :through => :tagged_items, :source => <name>'. Is it one of :taggable or :tag? 
+0

拋出什麼錯誤?你可以發佈嗎?也就是說,當你做「some_tag.products」時會發生什麼? – Stobbej 2013-02-11 15:58:11

+0

爲什麼你在TaggedItem上使用多態?由於一個TaggedItem和其他TaggedItem之間沒有關係,即在TaggedItem中; no has_many:tagged_items,:as =>:標記關聯。 – 2013-02-11 16:27:00

+0

@Stobbej我把你得到的錯誤,如果你做some_tag.products – Smickie 2013-02-11 17:25:20

回答

1

has_many :through協會的標籤模式無法從TaggedItem模型得到ProductImage源關聯。例如has_many :products, :through => :tagged_items將在TaggedItem中尋找直接關聯belongs_to :product,其在多態關聯的情況下被編寫爲belongs_to :taggable, :polymorphic => true。所以對於標籤模型,以瞭解該協會的確切來源我們需要添加一個選項:source,其類型爲:source_type

因此改變你的標籤模型關聯的樣子

class Tag < ActiveRecord::Base 
    has_many :tagged_items, :dependent => :destroy 
    has_many :products, :through => :tagged_items, :source => :taggable, :source_type => 'Product' 
    has_many :images, :through => :tagged_items, :source => :taggable, :source_type => 'Image' 
end 

這應該可以解決您的問題。 :)

0

當您設置標籤協會TaggedItem你不需要as選項。 :as => :taggable意味着標籤上的標籤是多態的,而不是。相反,另一方是,即,可以標記的項目,因爲你的名字聰明地表明瞭:)。

class Tag < ActiveRecord::Base 
    has_many :tagged_items, :dependent => :destroy 
    has_many :products, :through => :tagged_items 
    has_many :images, :through => :tagged_items 
end 
+0

我已經把你得到的錯誤,如果你做some_tag.products。 – Smickie 2013-02-11 17:25:50