0

我有两个用于标记的表,这样我就可以将标记附加到任何模型上,它的工作原理是这样的……</p>

有一个标记项连接表,它有一个 tag_id 列,然后是另外两个用于多态性的列:taggable_type 和 taggable_id…</p>

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?
4

2 回答 2

1

Tag 模型中的关联无法从模型中has_many :through获取源关联。例如,将在 TaggedItem 中寻找直接关联,在多态关联的情况下将其写为. 因此,为了让 Tag 模型了解关联的确切来源,我们需要添加一个选项及其类型为ProductImageTaggedItemhas_many :products, :through => :tagged_itemsbelongs_to :productbelongs_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

这应该可以解决您的问题。:)

于 2013-02-11T20:04:14.433 回答
0

as将标记关联设置到 TaggedItem 时 不需要该选项。: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
于 2013-02-11T16:19:33.240 回答