【发布时间】:2013-02-11 15:51:02
【问题描述】:
我有两个用于标记的表,因此我可以将标记附加到任何模型上,它的工作原理是这样的……
有一个标记项连接表,它有一个 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
问题在于标签模型,我似乎可以得到相反的工作,在标签模型上我想要一个 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?
【问题讨论】:
-
抛出什么错误?你能发帖吗?即,当您执行“some_tag.products”时会发生什么?
-
为什么要在 TaggedItem 上使用多态?由于一个 TaggedItem 与其他 TaggedItem 之间没有关系,即在 TaggedItem 中;没有 has_many :tagged_items, :as => :taggable 关联。
-
@Stobbej 我已经提出了如果你执行 some_tag.products 会出现的错误
标签: ruby-on-rails polymorphism has-many-through polymorphic-associations tagging