【问题标题】:How to bypass default_scope?如何绕过 default_scope?
【发布时间】:2012-04-01 22:04:54
【问题描述】:

我有一个具有以下 default_scope 的用户模型:

default_scope where(account_id: Account.current_account.id)

如果我调用User.all,我总是会根据当前帐户获得结果。

在某些情况下,出于管理目的,我想绕过该范围并查看系统中的所有用户,而不管帐户如何。

有没有办法做到这一点?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    是的,unscoped

    User.unscoped.all
    

    【讨论】:

    • 警告:查看 this answer 的 cmets 中关于使用 unscoped 解决此问题的注意事项。
    • 这不是一个很好的答案,我们刚刚经历了unscoped 完全破坏了我们在测试中的结果集的情况。
    【解决方案2】:

    如今,正确的方法是使用unscope,它只会删除范围的显式部分。例如:

    class User < ActiveRecord::Base
      default_scope where(account_id: Account.current_account.id)
      scope :all_accounts, -> { unscope(:account_id) }
    end
    

    这在您组合多个范围时很重要。

    当然,首先应用这种默认范围本身就是一种反模式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-04
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      相关资源
      最近更新 更多