简体   繁体   中英

Find records with more than one ActiveRecord HABTM Association

I've got two models, joined by a Has and Belongs To Many join table. Lets call these models User and Event. The majority of Users have 0 events, while few have one or more. I want to do something like:

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

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

I've found the answer:

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

Basically, the users .* restricts the result set to just the users table, and the DISTINCT keyword makes sure each user is only returned once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM