Question

I'm having trouble finding the best way to filter on a has_many through relationship directly with Active Record. I've found a bunch of posts here that almost address the issue but none of the answers have worked for me.

Group:

     has_many :taggings, as: :taggable
     has_many :tags, :through => :taggings

User:

     has_many :taggings, as: :taggable
     has_many :tags, :through => :taggings

I want to find all users who have tags that match a single groups tags

This following method works but I would rather assemble the list with a query.

    def interest_matches
      matched_users = Array.new
      self.tags.uniq.each do |tag|
        tag.users.map{ |u| matched_users.push(u) unless matched_users.include?(u) }
      end
      matched_users
    end

Any advice is much appreciated!

Was it helpful?

Solution

I am assuming that you are calling interest_matches on tags within a group of tags,

Minor note: you are calling self.tags.uniq twice, in lines 1 and 3 of the function. Also,

unless matched_users.include?(u) 

the above will iterate through the array every single time to check for existence of the user within the array, not the best option! Next time just call the .uniq method on it at the end.

Anyway, to answer your question, you probably want the join table to access the user's tags.

Method , may or may not work(hopefully it does):

 @matched = []
 group_of_tags = (i'm assuming this is predefined)
 @matched << User.joins(:tags).where(tag_name: group_of_tags.pluck(:name))
 @matched.uniq

Not 100% on this, but give it a go :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top