是否有方法否定范围的结果? 我有3个模型,由has_many关联:通过关联
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
之前,我想找到所有属于(已注册)培训的用户。在user.rb中,这有效:
scope :all_enrolled, -> { joins(:trainings) }
现在,我需要帮助才能找到所有不属于(未注册)培训的用户。我无法让这个工作:
scope :all_unenrolled, -> { !joins(:trainings) }
相反,它只是返回所有用户。像unenrolled users = (all users) - (enrolled users)
提前致谢。
答案 0 :(得分:4)
试试这个
scope : all_enrolled, -> { joins(:trainings) }
scope :not_enrolled, -> { where.not(id: all_enrolled) }