rei*_*mos 2 ruby activerecord scope ruby-on-rails
是否有否定范围结果的方法?我有3个模型,由has_many关联:通过关联
user.rb
class User < ActiveRecord::Base
has_many :user_training_maps
has_many :trainings, through: :user_training_maps
end
Run Code Online (Sandbox Code Playgroud)
training.rb
class Training < ActiveRecord::Base
has_many :user_training_maps
has_many :users, through: :user_training_maps
end
Run Code Online (Sandbox Code Playgroud)
user_training_map.rb
class UserTrainingMap < ActiveRecord::Base
belongs_to :user
belongs_to :training
end
Run Code Online (Sandbox Code Playgroud)
在此之前,我想查找所有属于(已注册)培训的用户。在user.rb中,这有效:
scope :all_enrolled, -> { joins(:trainings) }
现在,我需要帮助来查找不属于(未注册)培训的所有用户。我无法scope :all_unenrolled, -> { !joins(:trainings) }
使它起作用:
相反,它只是返回所有用户。就像是unenrolled users = (all users) - (enrolled users)
尝试这个
scope : all_enrolled, -> { joins(:trainings) }
scope :not_enrolled, -> { where.not(id: all_enrolled) }