mongoid/mongoid — Issue #1435: Change information unavailable when modifying relation collections
Author: chrisberkhout
Created: 2011-11-18 07:28:31+00:00
State: open

In my application, Document objects can have many Source objects.

When a document is updated, I need a callback to update related sources (those the document has after the update, but also any it had before the update). I can't know the pre-update sources if I do:

document.sources = []

It will only work if I do:

document.source_ids = []

Here's a more detailed example:

##[ given models ]##############################################################

class Document
include Mongoid::Document
has_and_belongs_to_many :sources
end
class Source
include Mongoid::Document
has_and_belongs_to_many :documents
end

##[ modifying by the relation ids => OKAY ]#####################################

document = Document.create(sources: [Source.new])

document.source_ids # => [BSON::ObjectId('4e409eba16e17727520000b6')]

document.source_ids = []
document.save

# in before_save, before_update, after_update, after_save
document.source_ids # => []
document.source_ids_was # => [BSON::ObjectId('4e409eba16e17727520000b6')]

document.source_ids # => []
document.source_ids_was # => []
document.previous_changes[:source_ids] # => [[BSON::ObjectId('4e409eba16e17727520000b6')], []]
document.sources # => [#]

document.reload

document.source_ids # => []
document.source_ids_was # => []
document.previous_changes[:source_ids] # => [[BSON::ObjectId('4e409eba16e17727520000b6')], []]
document.sources # => []

##[ modifying by the relation collection => PROBLEM ]###########################

document = Document.create(sources: [Source.new])

document.source_ids # => [BSON::ObjectId('4e409eba16e17727520000b6')]

document.sources = []
document.save

# in before_save, before_update, after_update, after_save
document.source_ids # => []
document.source_ids_was # => []

document.source_ids # => []
document.source_ids_was # => []
document.previous_changes[:source_ids] # => []
document.sources # => []

document.reload

document.source_ids # => []
document.source_ids_was # => []
document.previous_changes[:source_ids] # => []
document.sources # => []