views:

435

answers:

2

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.

+3  A: 

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.

jcnnghm
This does not solve the problem for a case where you want more than N results, and not just 1. Can anyone offer an AR way to do it, other than just raw SQL?
Asaf Bartov
A: 

Has anyone got the AR solution to this? I too am wondering how to find records in one model that have more than a certain number of records in a has_and_belongs_to_many association:

Product has_and_belongs_to_many :suppliers

Supplier has_and_belongs_to_many :products

Product.find(:all, :conditions => [ product.suppliers > 0 (this wont work) ])

Is it possible to do in AR?

Cheers

Shaun

Shaun