Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Find records that are not present another join table

I'm trying to write a ActiveRecord statment where I'm looking for all records where the id isn't present in another table...

Whats the syntax?

 @events =  Event.find(:all, :include => :personals, 
                  :conditions => ["event.id != ? ", @user.personal.event_id ])

Where personals is a join table that has the user_id and a event_id....

SO i'm essentially trying to find every event record that the user hasn't added to their own set of personal records....

Is there a better way to write this.... not null or something?

like image 657
ChrisWesAllen Avatar asked Jan 27 '11 15:01

ChrisWesAllen


2 Answers

The other answers don't scale well with hundreds of thousands or more records. Here's a pure SQL solution.

Rails 5+:

Event.left_outer_joins(:personals).where(personals: {event_id: nil})

This retrieves all Events that do not have an associated Personal.

Rails 3+:

Event.joins('LEFT JOIN personals ON event.id = personals.event_id').where('personals.event_id IS NULL')
like image 153
Benjamin Carlsson Avatar answered Oct 26 '22 21:10

Benjamin Carlsson


The solution presented by Nuby is as correct as ever. Here's the same query in a modern syntax, which can be used in Rails 3 and higher:

Event.where.not(id: @user.event_ids)
like image 21
Joost Baaij Avatar answered Oct 26 '22 21:10

Joost Baaij