范围的反轨

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)

Bal*_*hik 5

尝试这个

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

  • 从语义上来说,我同意这个例子更好,但 `explain` 表明查询更复杂,有两个 `where` 子句。因此,如果这对您很重要,那么 YMMV 具有查询速度。 (2认同)