Skip to content

Commit c6ae3df

Browse files
p-mongop
andauthored
MONGOID-5215 Document that or/nor conditions make default scope one of the disjunction branches (#5135)
Co-authored-by: Oleg Pudeyev <[email protected]>
1 parent 76eb3eb commit c6ae3df

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

source/reference/queries.txt

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1705,6 +1705,53 @@ that would affect its visibility within the scoped association.
17051705
label.bands # [ band ] Must reload.
17061706
label.reload.bands # []
17071707

1708+
.. note::
1709+
1710+
After the default scope is applied, it is no longer distinguished from
1711+
other query conditions. This can lead to surprising behavior when using
1712+
``or`` and ``nor`` operators in particular:
1713+
1714+
.. code-block:: ruby
1715+
1716+
class Band
1717+
include Mongoid::Document
1718+
1719+
field :name
1720+
field :active
1721+
field :touring
1722+
1723+
default_scope ->{ where(active: true) }
1724+
end
1725+
1726+
Band.where(name: 'Infected Mushroom')
1727+
# =>
1728+
# #<Mongoid::Criteria
1729+
# selector: {"active"=>true, "name"=>"Infected Mushroom"}
1730+
# options: {}
1731+
# class: Band
1732+
# embedded: false>
1733+
1734+
Band.where(name: 'Infected Mushroom').or(touring: true)
1735+
# =>
1736+
# #<Mongoid::Criteria
1737+
# selector: {"$or"=>[{"active"=>true, "name"=>"Infected Mushroom"}, {"touring"=>true}]}
1738+
# options: {}
1739+
# class: Band
1740+
# embedded: false>
1741+
1742+
Band.or(touring: true)
1743+
# =>
1744+
# #<Mongoid::Criteria
1745+
# selector: {"$or"=>[{"active"=>true}, {"touring"=>true}]}
1746+
# options: {}
1747+
# class: Band
1748+
# embedded: false>
1749+
1750+
In the last example, you might expect the two conditions
1751+
(``active: true`` and ``touring: true``) to be combined with an ``$and``,
1752+
but because the ``Band`` class already has the scope applied to it,
1753+
it becomes one of the disjunction branches of the ``or``.
1754+
17081755

17091756
Runtime Default Scope Override
17101757
------------------------------

0 commit comments

Comments
 (0)