tdahlke
tdahlke

Reputation: 287

Find all records NOT in a many-to-many association

In Rails 3 with ActiveRecord, I have 2 models (Users and Tasks). These models are linked together with a has_many :through association on another model, Assignments. How can I find all Tasks that are NOT associated to a particular user?

class User < ActiveRecord::Base
  has_many :assignments
  has_many :tasks, :through => :assignments
end

class Tasks < ActiveRecord::Base
  has_many :assignments
  has_many :users, :through => :assignments
end

class Assignments < ActiveRecord::Base
  belongs_to :users
  belongs_to :tasks
end

Upvotes: 1

Views: 1114

Answers (2)

noodl
noodl

Reputation: 17388

Short 'n sweet:

Task.all - user.tasks

Avoid loading user tasks:

Task.where('id not in (?)', user.task_ids)

I couldn't figure out how to do it with an outer join in AR.

Upvotes: 4

mark
mark

Reputation: 10564

I'm going to assume you want those tasks without any associated user, rather than not associated to a user in particular.

Tasks.joins('left outer join assignments on assignments.task_id = tasks.id').where('assignments.* is null')

Upvotes: 3

Related Questions