多个对象标签的多态查询

Polymorphic query for tags on multiple objects

我有一个 Author 模型 has_many :postshas_many :comments 它也可以是 taggable 基于 TaggingTag 模型我已经在下面发布了。

class Tagging
  belongs_to :tag
  belongs_to :taggable, polymorphic: true
end
class Tag
  has_many :taggings
  has_many :posts, through: :taggings, source: :taggable, source_type: 'Post'
  has_many :authors, through: :taggings, source: :taggable, source_type: 'Author'
end

这是我的 Author 模型的样子。

class Author
  has_many :posts
  has_many :comments
  has_many :taggings, as: :taggable
  has_many :tags, through: :taggings
end

我尝试了几种类型的查询,但我的所有尝试都会抛出错误,而且我不知道如何获取我想要的数据。基本上我想 运行 查询以下场景:

谢谢

如果您正在使用 gem acts_as_taggable,then its easy to find taggable records using tagged_with 实用程序。

##get the author
@author = Author.find params[:id]
##get the authors category/tags
cat = @author.tags
##find all post/comments that are tagged with cat
Author.includes(:post, :comments, :tags).tagged_with(cat,:any=>true)}.flatten.compact.uniq

如果您没有使用 acts_as_taggable :(,那么您必须构建自己的查询...可以像这样..

Author.includes(:post, :comments, :tags).where(tags: {taggable_type: 'Author',taggable_id: @author.id}).flatten.compact.uniq