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?
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')
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With