Rails ActsAsTaggable - Retrieve most_used tag of posts from user

64 Views Asked by At

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?

2

There are 2 best solutions below

2
O. Larkin On
ActsAsTaggableOn::Tag.joins(:taggable).where(taggable: current_user.posts).distinct.most_used(5)
0
GabrielTheCoder On

After tinkering around with a lot of queries I got the solution now which might be a bit tricky. Basically what ActsAsTaggableOn does is just assigning tags to the respective model. The tags however are in no way really related to anything else. What is possible is to assign tag ownership.

What I do now could be considered as bad practice: First the Post is assigned a tag which is stored in the tag_list, then I am going to trigger an after save action inside the posts.rb which grabs the last tag of the post object (only one tag can be assigned in my app) and assigns it to the user via

@user.tag(@post, with: "Some tag", on: :posts)

It would have been way easier to just code the whole thing myself and not rely on a gem, but its okay for now.