Forum: Ruby on Rails Find or select across a many to many relationship

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7e4e4ee43e45c1ab62f3bb21d6f4f566?d=identicon&s=25 johnsonmlw (Guest)
on 2009-03-01 18:53
(Received via mailing list)
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.
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-03-01 20:38
(Received via mailing list)
On Mar 1, 5:52 pm, johnsonmlw <johnson...@gmail.com> wrote:
> 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.
> @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
7e4e4ee43e45c1ab62f3bb21d6f4f566?d=identicon&s=25 johnsonmlw (Guest)
on 2009-03-01 22:35
(Received via mailing list)
Oh yes. Very nice. Thanks.

AR is very aware! Clever AR!

--
Matt

On Mar 1, 7:37 pm, Frederick Cheung <frederick.che...@gmail.com>
This topic is locked and can not be replied to.