【问题标题】:rails inverse of a scoperails 范围的倒数
【发布时间】:2018-06-24 17:24:23
【问题描述】:

是否有否定作用域结果的方法? 我有 3 个模型,由 has_many 关联:通过关联

用户.rb

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

培训.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, -&gt; { joins(:trainings) }

现在,我需要帮助找到所有不属于(未注册)培训的用户。我不能让它工作: scope :all_unenrolled, -&gt; { !joins(:trainings) } 相反,它只是返回所有用户。类似unenrolled users = (all users) - (enrolled users)

【问题讨论】:

    标签: ruby-on-rails ruby activerecord scope


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 语义上我同意这个例子更好,但explain 表明查询更复杂,有两个where 子句。因此,如果这对您很重要,那么 YMMV 具有查询速度。
    【解决方案2】:

    ActiveRecord 已经有一段时间了 left_joins,所以你应该可以像编写普通 SQL 一样直接执行它:

      scope :not_enrolled, { left_joins(:trainings).where(trainings: {id: nil}) } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 2012-11-07
      相关资源
      最近更新 更多