logandk/mongoid_denormalize — Issue #6: denormalize_to triggers target object callback lifecycle via update_attributes
Author: dzello
Created: 2012-01-27 00:00:08+00:00
State: open

The Setup:
attr_accessible is being used on a model that is denormalized_to (aka the target model).
The denormalized fields (i.e. sourcemodel_field) have not been made attr_accessible

What happens:
When the source model is saved and the denormalize_to callbacks fire, the update_attributes call near the end of MongoidDenormalize#denormalize_to will not update some or all of the target attributes (mass-assignment warning, etc). So the target record is not yet modified.

Next, the target model's save callback chain will be executed b/c update_attributes is being used. If the target model is also denormalizing from the source model, the target model *will* actually get the new values. The attr_accessible doesn't matter b/c the values are set with =.

So, while everything works in the end, what actually happens in a bit surprising and even in the case where attr_accessible isn't in play, triggering the callback cycle on the target object is extra overhead. And in some cases could cause circular dependencies (e.g. 2 one-to-one models that are denormalizing to each other).

A few suggestions then:
1 - Set the fields in denormalize_to the same way as in denormalize from. (alternatively, point out in the docs that the developer needs to manually add attr_accessible)
2 - Instead of using update_attributes, use an alternative saving method that does not trigger callbacks on the target model.

Great concept altogether though and I hope you keep going on it.