Closed mikwat closed 6 years ago
1 Warning | |
---|---|
:warning: | Unless you’re refactoring existing code, please update CHANGELOG.md. |
Here's an example of a CHANGELOG.md entry:
* [#214](https://github.com/mongoid/mongoid-history/pull/214): Solution for tracking has_and_belongs_to_many relations - [@mikwat](https://github.com/mikwat).
Generated by :no_entry_sign: danger
Is the expected behavior, @dblock ? Basically, it appears that updates to has_and_belongs_to_many
relations aren't tracked.
I would expect everything to be tracked, so we should call this a bug. Feel free to try a fix!
@dblock When you have a chance, let me know your thoughts.
I think we should be able to attach those callbacks by examining all HABTM relationships in late binding, similarly to how we examine tracked fields. This would avoid the whole explicit options to the relationship, wouldn't it?
That would be great, but I'm not sure it's possible. reflect_on_all_associations(:has_and_belongs_to_many)
returns an array of Mongoid::Relations::Metadata instances, but how would you use these to add the necessary callbacks on the relation?
Maybe @estolfo can help with some pointers, please?
@mikwat Unrelated, but to just keep the parent repo clean maybe work off a fork? My OCD is kicking in :)
Of course @dblock Sorry about that.
Currently,
has_and_belongs_to_many
relations are not tracked consistently. For example:Given the following models:
Create with tags works as expected:
However, changes are not recorded:
Unfortunately, none of the document callbacks (i.e.
around_update
,around_create
,around_destroy
) are called when modifications are made to ahas_and_belongs_to_many
relation. From my reading of the Mongoid docs and code, the only way to be notified of changes to these relations is to attach a callback directly to the relation definition.While inconvenient, this proposed solution simply makes a callback method available that must be attached to each
has_and_belongs_to_many
relation viabefore_add: :track_has_and_belongs_to_many, before_remove: :track_has_and_belongs_to_many
. I don't know of a way to automatically attach these callbacks, but please educate me if this is possible.Here's an example of this solution in use: