多个对象标签的多态查询
Polymorphic query for tags on multiple objects
我有一个 Author
模型 has_many :posts
,has_many :comments
它也可以是 taggable
基于 Tagging
和 Tag
模型我已经在下面发布了。
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
我尝试了几种类型的查询,但我的所有尝试都会抛出错误,而且我不知道如何获取我想要的数据。基本上我想 运行 查询以下场景:
- 假设我有一个作者对象
@author = Author.find(1)
。我将如何获取所有相关的评论和帖子按作者创建的标签分组?我不确定如何构建这个 AR 对象。
- 我如何找到共享特定标签的作者的所有评论和帖子?为此,我尝试了
@taggable = @author.tagging.joins(:tag).where(tags: {name: @tag_name})
,但我做不到。
谢谢
如果您正在使用 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
我有一个 Author
模型 has_many :posts
,has_many :comments
它也可以是 taggable
基于 Tagging
和 Tag
模型我已经在下面发布了。
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
我尝试了几种类型的查询,但我的所有尝试都会抛出错误,而且我不知道如何获取我想要的数据。基本上我想 运行 查询以下场景:
- 假设我有一个作者对象
@author = Author.find(1)
。我将如何获取所有相关的评论和帖子按作者创建的标签分组?我不确定如何构建这个 AR 对象。 - 我如何找到共享特定标签的作者的所有评论和帖子?为此,我尝试了
@taggable = @author.tagging.joins(:tag).where(tags: {name: @tag_name})
,但我做不到。
谢谢
如果您正在使用 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