1

我正在编写一些棘手的多态关系来处理标记。

我有一个Tag模型和一个Tagging属于多态的模型taggable

我有一个Item模型,它has_many :taggings, :as => :taggable,和has_many :tags, :through => :taggings,所以我可以调用@item.tags

这一切正常。

我想将另一个模型加入到组合中-a Storewhich has_many :items。我希望能够使用@store.tags.

这是我所拥有的:

class Store < AR::Base
  has_many :items
  has_many :tags, :through => :items, :source => :taggings

但是,这将返回taggings与商店中的所有项目相关联的,而不是实际的标签。

如何通过项目、标签指定商店 has_many 标签?

如果需要,可以发布更多信息 - 试图防止信息过载!谢谢 :)

4

2 回答 2

2

关联的来源has_many必须是belongs_tohas_one带选项的has_many关联(感谢此答案的信息)。:through

有些人已经成功使用了一个插件,但在我的情况下,它似乎无法与我的taggable多态关联正常工作。

目前,我的解决方案是将finder_sql选项传递给has_many

class Store < ActiveRecord::Base
  has_many :items
  has_many :tags, :finder_sql => 
    'SELECT tags.* from tags
      INNER JOIN taggings on tags.id = taggings.tag_id
      INNER JOIN items on items.id = taggings.taggable_id AND taggings.taggable_type = "Item"
      WHERE items.store_id = #{id}'

end
于 2010-08-05T04:23:02.007 回答
0

你可以用普通的 Ruby 做:

site.wares.map(&:tags).flatten.uniq

除非您的标签/商品/物品数量很少,否则这将是低效的。

于 2010-08-02T15:23:25.933 回答