我有两个用于标记的表,以便我可以将标记附加到任何模型,它的工作原理如此...
有一个标记项连接表,其中包含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?
答案 0 :(得分:1)
您的代码模型中的has_many :through
关联无法从Product
模型中获取Image
和TaggedItem
的源关联。例如has_many :products, :through => :tagged_items
将在TaggedItem中查找直接关联belongs_to :product
,在多态关联的情况下,该关联被写为belongs_to :taggable, :polymorphic => true
。因此,要让Tag模型了解关联的确切来源,我们需要添加选项:source
,其类型为:source_type
因此,将您的Tag模型关联更改为
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
这应该可以解决您的问题。 :)
答案 1 :(得分:0)
在将Tag关联设置为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