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)
Try this
scope : all_enrolled, -> { joins(:trainings) }
scope :not_enrolled, -> { where.not(id: all_enrolled) }
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