Skip to content

MONGOID-5078 add tests and documentation pertaining to atomic_selector usage in Mongoid #4985

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions docs/tutorials/mongoid-persistence.txt
Original file line number Diff line number Diff line change
Expand Up @@ -220,18 +220,36 @@ operations with examples.
* - ``Model#delete``

*Deletes the document from the database without running callbacks.*

*If the document is not persisted, Mongoid will attempt to delete from
the database any document with the same* ``_id``.
-
.. code-block:: ruby

person.delete

person = Person.create!(...)
unsaved_person = Person.new(id: person.id)
unsaved_person.delete
person.reload
# raises Mongoid::Errors::DocumentNotFound because the person was deleted

* - ``Model#destroy``

*Deletes the document from the database while running destroy callbacks.*

*If the document is not persisted, Mongoid will attempt to delete from
the database any document with the same* ``_id``.
-
.. code-block:: ruby

person.destroy

person = Person.create!(...)
unsaved_person = Person.new(id: person.id)
unsaved_person.destroy
person.reload
# raises Mongoid::Errors::DocumentNotFound because the person was deleted

* - ``Model.delete_all``

Expand Down
31 changes: 31 additions & 0 deletions docs/tutorials/mongoid-queries.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1542,6 +1542,37 @@ nonexistent field ``deregistered_at`` the date was interpreted to be in UTC
and converted to a time, matching the behavior of querying a ``Date`` field.


Reloading
=========

Use the ``reload`` method to fetch the most recent version of a document from
the database:

.. code-block:: ruby

band = Band.find(..)
band.reload

If the model has a :ref:`shard key <shard-keys>` defined, the shard key value
is included in the reloading query.

.. note::

``reload`` also works when the document has not been persisted, in which case
it performs a query using the ``id`` value (and shard key value, if a shard
key is defined):

.. code-block:: ruby

existing = Band.create!(name: 'Photek')

# Unsaved document
band = Band.new(id: existing.id)
band.reload
band.name
# => "Photek"


Queries + Persistence
=====================

Expand Down
70 changes: 70 additions & 0 deletions docs/tutorials/mongoid-relations.txt
Original file line number Diff line number Diff line change
Expand Up @@ -747,6 +747,76 @@ A future version of Mongoid may allow removing previously defined fields.
by their content attribute values during queries, updates and deletes.


Deleting
--------

Mongoid provides three methods for deleting children from ``embeds_many``
associations: ``clear``, ``destroy_all`` and ``delete_all``.

``clear``
`````````

The ``clear`` method uses the :manual:`$unset operator
</reference/operator/update/unset>` to remove the entire association from the
host document. It does not run destroy callbacks on the documents being removed,
acting like ``delete_all` in this regard:

.. code-block:: ruby

band = Band.find(...)
band.tours.clear

If ``clear`` is called on an association in an unsaved host document, it will
still try to remove the association from the database based on the host
document's ``_id``:

.. code-block:: ruby

band = Band.find(...)
band.tours << Tour.new(...)

unsaved_band = Band.new(id: band.id, tours: [Tour.new])
# Removes all tours from the persisted band due to _id match.
unsaved_band.tours.clear

band.tours
# => []

``delete_all``
``````````````

The ``delete_all`` method removes the documents that are in the association
using the :manual:`$pullAll operator </reference/operator/update/pullAll>`.
Unlike ``clear``, ``delete_all``:

- Loads the association, if it wasn't yet loaded;
- Only removes the documents that exist in the application.

``delete_all`` does not run destroy callbacks on the documents being removed.

Example:

.. code-block:: ruby

band = Band.find(...)
band.tours.delete_all


``destroy_all``
```````````````

The ``delete_all`` method removes the documents that are in the association
using the :manual:`$pullAll operator </reference/operator/update/pullAll>`
while running the destroy callbacks. Like ``delete_all``, ``destroy_all``
loads the entire association if it wasn't yet loaded and it only removes
documents that exist in the application:

.. code-block:: ruby

band = Band.find(...)
band.tours.destroy_all


Common Behavior
===============

Expand Down
11 changes: 9 additions & 2 deletions lib/mongoid/association/embedded/embeds_many/proxy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,15 @@ def build(attributes = {}, type = nil)

alias :new :build

# Clear the association. Will delete the documents from the db if they are
# already persisted.
# Clear the association. Will delete the documents from the db
# if they are already persisted.
#
# If the host document is not persisted but its _id matches a
# persisted document, calling #clear on an association will remove
# the association's documents from the database even though the
# set of documents in the application (as loaded in the host)
# is different from what is in the database, and the host may
# not contain any persisted documents in the association either.
#
# @example Clear the association.
# person.addresses.clear
Expand Down
12 changes: 5 additions & 7 deletions lib/mongoid/selectable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ module Selectable
# @since 1.0.0
def atomic_selector
@atomic_selector ||=
(embedded? ? embedded_atomic_selector : root_atomic_selector)
(embedded? ? embedded_atomic_selector : root_atomic_selector_in_db)
end

private
Expand All @@ -44,18 +44,16 @@ def embedded_atomic_selector
end
end

# Get the atomic selector for a root document.
# Get the atomic selector that would match the existing version of the
# root document.
#
# @api private
#
# @example Get the root atomic selector.
# document.root_atomic_selector
#
# @return [ Hash ] The root document selector.
#
# @since 4.0.0
def root_atomic_selector
{ "_id" => _id }.merge!(shard_key_selector)
def root_atomic_selector_in_db
{ "_id" => _id }.merge!(shard_key_selector_in_db)
end
end
end
26 changes: 21 additions & 5 deletions lib/mongoid/shardable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,31 @@ def shard_key_fields
self.class.shard_key_fields
end

# Get the document selector with the defined shard keys.
#
# @example Get the selector for the shard keys.
# person.shard_key_selector
# Returns the selector that would match the current version of this
# document.
#
# @return [ Hash ] The shard key selector.
#
# @since 2.0.0
# @api private
def shard_key_selector
selector = {}
shard_key_fields.each do |field|
selector[field.to_s] = send(field)
end
selector
end

# Returns the selector that would match the existing version of this
# document in the database.
#
# If the document is not persisted, this method uses the current values
# of the shard key fields. If the document is persisted, this method
# uses the values retrieved from the database.
#
# @return [ Hash ] The shard key selector.
#
# @api private
def shard_key_selector_in_db
selector = {}
shard_key_fields.each do |field|
selector[field.to_s] = new_record? ? send(field) : attribute_was(field)
Expand Down
44 changes: 44 additions & 0 deletions spec/integration/associations/embeds_many_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,48 @@
end
end
end

context 'clearing association when parent is not saved' do
let!(:parent) { Canvas.create!(shapes: [Shape.new]) }

let(:unsaved_parent) { Canvas.new(id: parent.id, shapes: [Shape.new]) }

context "using #clear" do
it 'deletes the target from the database' do
unsaved_parent.shapes.clear

unsaved_parent.shapes.should be_empty

unsaved_parent.new_record?.should be true
parent.reload
parent.shapes.should be_empty
end
end

shared_examples 'does not delete the target from the database' do
it 'does not delete the target from the database' do
unsaved_parent.shapes.should be_empty

unsaved_parent.new_record?.should be true
parent.reload
parent.shapes.length.should == 1
end
end

context "using #delete_all" do
before do
unsaved_parent.shapes.delete_all
end

include_examples 'does not delete the target from the database'
end

context "using #destroy_all" do
before do
unsaved_parent.shapes.destroy_all
end

include_examples 'does not delete the target from the database'
end
end
end
76 changes: 64 additions & 12 deletions spec/mongoid/atomic/paths_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,33 @@
person.addresses << address
end

it "returns the association with id.atomic_selector" do
expect(address.atomic_selector).to eq(
{ "_id" => person.id, "addresses._id" => address.id }
)
context 'when the parent is persisted' do

let(:person) do
Person.create!
end

before do
person.should be_persisted
end

it "returns the association with id.atomic_selector" do
expect(address.atomic_selector).to eq(
{ "_id" => person.id, "addresses._id" => address.id }
)
end
end

context 'when the parent is not persisted' do
before do
person.should be_new_record
end

it "returns the association with id.atomic_selector" do
expect(address.atomic_selector).to eq(
{ "_id" => person.id, "addresses._id" => address.id }
)
end
end
end

Expand All @@ -127,14 +150,43 @@
person.addresses << address
end

it "returns the JSON notation to the document with ids" do
expect(location.atomic_selector).to eq(
{
"_id" => person.id,
"addresses._id" => address.id,
"addresses.locations._id" => location.id
}
)
context 'when the parent is persisted' do

let(:person) do
Person.create!
end

before do
person.should be_persisted
end

it "returns the JSON notation to the document with ids" do
expect(location.atomic_selector).to eq(
{
"_id" => person.id,
"addresses._id" => address.id,
"addresses.0.locations._id" => location.id
}
)
end
end

context 'when the parent is not persisted' do
before do
person.should be_new_record
end

it "returns the JSON notation to the document with ids" do
expect(location.atomic_selector).to eq(
{
"_id" => person.id,
"addresses._id" => address.id,
# This condition is technically acceptable for finds
# but probably won't work for modifications of 'locations'.
"addresses.locations._id" => location.id
}
)
end
end
end
end
Expand Down
Loading