Fetch record based on many to many association

20 views
Skip to first unread message

Linus Pettersson

unread,
Feb 20, 2013, 2:20:46 PM2/20/13
to rubyonra...@googlegroups.com
Hi

Let's say I have three models, Company, User and Entry (and a join model EntryParticipants).

Company has many Users, a User has many Entries (Entries created by a User).
Also, there is another many-to-many relationship between User and Entry (a User can participate in many entries and an Entry can have many participants).

So, now I want to fetch all Entries that a User has created OR is participating in. I'm a bit stuck though...

user.entries => All entries created by this user
user.participated_entries => All participated entries

But now I want to get them all in one query. The code below is working, but is there a more efficient way to do it?

scope.includes(:entry_participants).where("(entry_participants.participated_entry_id = entries.id) OR entries.user_id = ?", user.id)

javinto

unread,
Feb 21, 2013, 10:11:49 AM2/21/13
to rubyonra...@googlegroups.com
Why bother and not doing:

(user.entries + user.participated_entries).uniq

I wonder if a complicated single query is must faster....

Op woensdag 20 februari 2013 20:20:46 UTC+1 schreef Linus Pettersson het volgende:

Matt Jones

unread,
Feb 22, 2013, 12:57:55 PM2/22/13
to rubyonra...@googlegroups.com
If it makes sense for your domain model, adding some logic to enforce that the user who created the Entry is always also a participant makes this trivial. 

--Matt Jones 
Reply all
Reply to author
Forward
0 new messages