0
class Event
  has_many :keywords, :through => :event_keywords
end

class User 
  has_many :keywords, :through => :user_keywords
end

I have a User method that calculates an event's relevance based on the keywords it shares with a specific user:

User.rb

def calculate_event_relevance(event_id)
    event_keywords = event.keywords

    event_keywords.each do |kw|
        user_keyword_match = self.keywords.where(id: kw.id).first

        if user_keyword_match
             ## do some stuff
        end
    end
end

Right now, I am looping through each keyword. In the loop, I make a query to see if the user also has that keyword.

Is there a way instead to make one single query (and save it to event_keywords) that only returns the event.keywords that a user also has so that I don't need to loop through all of them?

Is there a query that can find which keywords a user and event have in common?

1 Answer 1

1

Assuming that event_keywords and user_keywords are both arrays, you can use the & on the array to get the values that are present in both.

For example,

[1,2,3,4,5,9] & [5,6,7,8,9] #=> [5, 9]

In this case, 5 and 9 are present in both arrays so they are returned as a result.

In your case, you can do something like

share_keywords = event.keywords & self.keywords

To return an array with all the keywords shared between event and user. Then you can iterate through that and do what you need to do.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks @davidhu2000 ! That is so much easier than I thought :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.