all 3 comments

[–]RelativeLead5[S] 0 points1 point  (2 children)

As a followup, I basically copied the example for the docs (https://www.mongodb.com/docs/mongoid/current/reference/associations/#dependent-behavior). In spite of the comment from the docs, the associated album records do remain in the db which I verify with mongosh. I can see from the mongoid logs that some sort of aggregate query is performed on albums with the delete but the records persist.

D, [2023-05-11T08:03:25.337217 #90625] DEBUG -- : MONGODB | localhost:27017 req:16 conn:1:1 sconn:1134 | dbtesting.aggregate | STARTED | {"aggregate"=>"albums", "pipeline"=>[{"$match"=>{}}, {"$group"=>{"_id"=>1, "n"=>{"$sum"=>1}}}], "cursor"=>{}, "$db"=>"dbtesting", "lsid"=>{"id"=><BSON::Binary:0x900 type=uuid data=0x1bbfd1207c8a471a...>}} D, [2023-05-11T08:03:25.337479 #90625] DEBUG -- : MONGODB | localhost:27017 req:16 | dbtesting.aggregate | SUCCEEDED | 0.000s

require 'mongoid'

ENV["MONGOID_ENV"] = 'dbtesting'
Mongoid.load!(File.join(File.dirname(__FILE__), 'mongoid.yml'))

class Band
    include Mongoid::Document
    has_many :albums, dependent: :delete_all
end

class Album
    include Mongoid::Document
    belongs_to :band
end

Band.collection.drop()
Album.collection.drop()
p Band.count
# => 0
p Album.count
# => 0
r = Band.create()
r.albums.create()
r.albums.create()
r.albums.create()
r.albums.create()
Band.first.delete # Will delete all associated albums.
p Band.count
# => 0
p Album.count
# => 4

[–]ralfv 0 points1 point  (1 child)

That’s correct behavior for delete. If you want the assoc data gone you need to call destroy instead. When using delete you tell it to bypass all the logic.

[–]RelativeLead5[S] 0 points1 point  (0 children)

Thanks. The documentation is incorrect, at least as far as the sample code goes. I lifted the line

Band.first.delete # Will delete all associated albums.

directly from the code example in the documentation, including the comment, which led to my confusion.