I have two modules that add to the default scope for objects.

module Testable
  extend ActiveSupport::Concern

  included do
    default_scope { where(test_only: false) }
  end
end

module ActiveScoped
  extend ActiveSupport::Concern

  included do
    default_scope { where(active: true) }
  end
end

When I include both these modules in a model class, the query has both these clauses in the where. The reason why these both have to be a default scope is because there are many more places where these scopes have to be applied than not. Further, the cost of forgetting to apply the scope in one of these many places is high. Hence, specifying explicitly in the few places it doesn't apply seems like a better alternative. However, I now need to write a method that can get me all objects from a model with only one of these scopes applied. How can I do that?

Any help will be much appreciated.

有帮助吗?

解决方案

I don't like the idea to define default_scope within a module and then include it. This would sound more natural to be the job of model itself.

However, you can still use unscoped to remove these default scopes.

Foo.all
# Returns relation object with current two default scopes

Foo.unscoped
# Returns all results without any scope

Foo.unscoped do
  where(active: true)
end
# Returns object with only one scope applied
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top