Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails inverse of a scope

Is there a method to negate the result of a scope? I have 3 models, associated by has_many :through association

user.rb

class User < ActiveRecord::Base
    has_many :user_training_maps
    has_many :trainings, through: :user_training_maps
end

training.rb

class Training < ActiveRecord::Base
    has_many :user_training_maps
    has_many :users, through: :user_training_maps
end

user_training_map.rb

class UserTrainingMap < ActiveRecord::Base
    belongs_to :user
    belongs_to :training
end

Before, I want to find all users belonging (enrolled) to a training. In user.rb, this works:

scope :all_enrolled, -> { joins(:trainings) }

Now, I need help to find all users NOT belonging (unenrolled) to a training. I can't get this to work: scope :all_unenrolled, -> { !joins(:trainings) } instead, it simply returns all the users. Something like unenrolled users = (all users) - (enrolled users)

like image 601
reiallenramos Avatar asked Dec 24 '22 11:12

reiallenramos


1 Answers

Try this

scope : all_enrolled, -> { joins(:trainings) } scope :not_enrolled, -> { where.not(id: all_enrolled) }

like image 157
Bala Karthik Avatar answered Jan 05 '23 01:01

Bala Karthik