Search for entries with multiple ActiveRecord HABTM associations

I have two models that Has and Belongs To Many join to. Lets name these models User and Event. Most users have 0 events, while few have one or more. I want to do something like:

User.find (: all ,: joins =>: events ,: conditions => [" " Something that counts events >? "], 0)

The problem is that I'm not sure how to select only users who have 1 or more related events.

+4
source share
1 answer

I found the answer:

User.find(:all, :joins => :events, :select => 'DISTINCT `users`.*') 

In principle, users . * restricts the result set to only the user table, and the DISTINCT keyword ensures that each user is returned only once.

+4
source

Source: https://habr.com/ru/post/1277755/


All Articles