NoBrainer allows named scopes to be defined on Models. Scopes are defined by declaring a class method on a model. Such method must return a criterion. Example:
You can also use the
scope method which defines a class method with
whatever you pass as a block. Example:
When a class method is found in a chain of criteria, the method is executed and the returned criterion is merged with the chain. Example with the previously declared scope:
Scopes can accept arguments. Example:
Default scopes are scopes that are merged in criteria when constructing a query.
unscoped in the criteria will disable the use of the default scope.
Note that many default scopes can be declared. All of them are applied, in the order of declaration. This can come in handy when using polymorphic models with different default scopes declared in parents and subclasses. Example:
Default scopes are applied at the beginning of the chain when building a query.
unscoped keyword has no effect on
has_many associations have a custom
Unlike the ActiveRecord behavior,
where() filters in default scopes are not overridable.
For example, consider a Model with a default scope of
where(:active => true).
Model.where(:active => false) will yield all inactive
models, while NoBrainer will return nothing. This is because NoBrainer
Model.where(:active => true).where(:active => false), which evaluates to
Model.where(:and => [:active => true, :active => false]).
Default Scopes are sometimes ignored
NoBrainer will not use the default scopes in the following cases:
- When using a
dependentoption on an association, such as
has_many :stuff, :dependent => :destroy, the Stuff model is used unscoped. For example, upon destroy, NoBrainer will perform a
- When using
validates_uniqueness_of :some_field, NoBrainer will not use the default scope to find any duplicates of
- When using