【问题标题】:Rails - has many polymorphic tagging not working correctlyRails - 有许多多态标记无法正常工作
【发布时间】: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


【解决方案1】:

标签模型中的has_many :through 关联无法从TaggedItem 模型中获取ProductImage 的源关联。例如has_many :products, :through =&gt; :tagged_items 将在 TaggedItem 中查找直接关联 belongs_to :product,如果是多态关联,则将其写为 belongs_to :taggable, :polymorphic =&gt; true。因此,为了让 Tag 模型了解关联的确切来源,我们需要添加一个选项 :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

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

【讨论】:

    【解决方案2】:

    在将标签关联设置到 TaggedItem 时,您不需要 as 选项。 :as =&gt; :taggable 意味着标记项目上的标记是多态的,但它不是。相反,另一面是,即,您的名字巧妙地暗示了可标记的项目:)。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      相关资源
      最近更新 更多