Home > Mobile >  Rails ActsAsTaggable - Retrieve most_used tag of posts from user
Rails ActsAsTaggable - Retrieve most_used tag of posts from user

Time:06-25

With the ActsAsTaggableOn gem I would like to retrieve the most used tags used for posts by a certain user. Currently I have a user.rb model and a post.rb model which belongs_to the user. What I can do is this:

ActsAsTaggableOn::Tag.most_used

Which does show me the most used tags used overall. However, I would like to filter that down to only show me the most used tags by the current_user. I was thinking of something like:

ActsAsTaggableOn::Tag.most_used.joins(:posts).where(user_id: current_user.id)

which does not work since there is no connection established and therefore i cant join the models. How can I access the most used tags in the posts by the current_user?

CodePudding user response:

ActsAsTaggableOn::Tag.joins(:taggable).where(taggable: current_user.posts).distinct.most_used(5)

CodePudding user response:

Taggable#most_used takes advantage of a counter_cache column named taggings_count. This column stores how ofter the specific tag has been used.

Unfortunately, you cannot use this to return how often a tag has been used by a specific user or a specific user's most used tags. That means you would need determine this on your own without using the most_used method.

The following might work for you:

ActsAsTaggableOn::Tag
  .select("#{ActsAsTaggableOn.tags_table}.*, COUNT(posts.id) AS tag_count")
  .joins(taggings: :taggable)                  # join associations by their names in ActsAsTaggableOn
  .where(posts: { user_id: current_user.id } ) # only for a specific user (how the tables are named in the database)
  .group("#{ActsAsTaggableOn.tags_table}.id")  # needed to make SQL COUNT work as expected
  .order('tag_count DESC')                     # sort by count descending
  .limit(20)                                   # pick the 20 most used  entries
  
  • Related