Skip to content

Commit 89caac6

Browse files
p-mongop
andauthored
MONGOID-5186 .with_scope should restore previous scope (#5127)
Co-authored-by: Oleg Pudeyev <[email protected]>
1 parent b7b8651 commit 89caac6

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

source/reference/queries.txt

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1577,6 +1577,7 @@ To have Mongoid raise an error when a scope would overwrite an existing class
15771577
method, set the ``scope_overwrite_exception`` :ref:`configuration option
15781578
<configuration-options>` to ``true``.
15791579

1580+
15801581
Default Scopes
15811582
--------------
15821583

@@ -1705,6 +1706,35 @@ that would affect its visibility within the scoped association.
17051706
label.reload.bands # []
17061707

17071708

1709+
Runtime Default Scope Override
1710+
------------------------------
1711+
1712+
You can use the ``with_scope`` method to change the default scope in a block
1713+
at runtime:
1714+
1715+
.. code-block:: ruby
1716+
1717+
class Band
1718+
include Mongoid::Document
1719+
field :country, type: String
1720+
field :genres, type: Array
1721+
1722+
scope :english, ->{ where(country: "England") }
1723+
end
1724+
1725+
criteria = Band.with_scope(Band.english) do
1726+
Band.all
1727+
end
1728+
1729+
criteria
1730+
# =>
1731+
# #<Mongoid::Criteria
1732+
# selector: {"country"=>"England"}
1733+
# options: {}
1734+
# class: Band
1735+
# embedded: false>
1736+
1737+
17081738
Class Methods
17091739
-------------
17101740

0 commit comments

Comments
 (0)