Find or select across a many to many relationship

I have an incident model and a pupil model, and they have a many to many relationship through an involvement model. Also, a pupil belongs to a cohort.

How can I show incidents (ideally just once), in date order, where there is an involvement present from a pupil where their pupil.cohort_id == 1 ?

At the moment, I'm finding all pupils where pupil.cohort_id ==1, then iterating through the @pupils, listing the involvements/incident details for those pupils. But this isn't great, as (i) incidents show up more than once where two pupils are involved in the incident, and (ii) I can't order by incident date. It feels backwards.

I suspect maybe I can use

@incidents = Incident.find(:all) @incidents = @incidents.select {|i| ... something something to do with involvements then pupil.cohort_id == 1?

Maybe I'm miles off?

Help or clues appreciated.

I have an incident model and a pupil model, and they have a many to many relationship through an involvement model. Also, a pupil belongs to a cohort.

How can I show incidents (ideally just once), in date order, where there is an involvement present from a pupil where their pupil.cohort_id == 1 ?

One way would be something like Incident.find :all, :joins => :pupil, :conditions => ["pupils.cohort_id = ?", 1] This joins the pupils table (AR is smart enough to know that in needs to join the involvements tables as well) and then you can easily apply conditions on pupils order stuff etc...

You'll need to put a distinct in there not to get duplicate rows.

At the moment, I'm finding all pupils where pupil.cohort_id ==1, then iterating through the @pupils, listing the involvements/incident details for those pupils. But this isn't great, as (i) incidents show up more than once where two pupils are involved in the incident, and (ii) I can't order by incident date. It feels backwards.

I suspect maybe I can use

@incidents = Incident.find(:all) @incidents = @incidents.select {|i| ... something something to do with involvements then pupil.cohort_id == 1?

Anything that starts with Foo.find(:all) will run out of steam when there starts to be a large number of foos.

Fred

Oh yes. Very nice. Thanks.

AR is very aware! Clever AR!