Search code examples
ruby-on-railspolymorphic-associations

Polymorphic query for tags on multiple objects


I have an Author model that has_many :posts, has_many :comments it also can be taggable based on the Tagging and Tag models that I've posted below.

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

Here's what my Author model looks like.

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

There are a few types of queries that I'm attempted but all of my attempts throw errors, and I can't wrap my head around how to get to the data I want. Basically I'd like to run queries for the following scenarios:

  • Let's say I have an author object @author = Author.find(1). How would I go about getting all related comments and posts grouped by tags that the author has created? I'm not sure how to build this AR object.
  • How would I find all comments and posts by an author that share a specific tag? For this I've tried @taggable = @author.tagging.joins(:tag).where(tags: {name: @tag_name}), but I can't do that.

Thanks


Solution

  • If you are using the gem acts_as_taggable,then its easy to find taggable records using tagged_with utility.

    ##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
    

    IF,you are not using acts_as_taggable :(,then you have to construct your own query...which can be like this..

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