2012-04-01 74 views
13

我有具有以下default_scope用戶模式:如何繞過default_scope?

default_scope where(account_id: Account.current_account.id)

如果我打電話User.all我總是根據當前帳戶的結果。

在某些情況下,出於管理目的,我想繞過該範圍並查看系統中的所有用戶,而不考慮帳戶。

有沒有辦法做到這一點?

回答

20

是的,用unscoped

User.unscoped.all 
+0

完美,謝謝! – Nathan 2012-04-01 22:19:29

+2

_警告:_檢查在[這個答案](http://stackoverflow.com/a/4166950/2859525)關於使用'unscoped'解決這個問題的注意事項。 – Todd 2016-12-30 21:24:53

+0

這不是一個好的答案,我們剛剛經歷了一種情況,'unscoped'在測試中完全毀了我們的結果集。 – 2017-05-26 13:33:06

0

這些天來,正確的方法是使用unscope,這將只刪除範圍的明確組成部分。例如:

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

當你編寫多個作用域時,這很重要。

當然,首先應用這種默認範圍是它自身的反模式。