Fields don't update when many-to-many items are added or removed #6

mattjoss opened this Issue Jun 6, 2012 · 5 comments


None yet
2 participants

mattjoss commented Jun 6, 2012

Appreciate the work you have one on this. It's a great resource to have. The following issue may be user error. I apologize if it is.

Take the Head/Person sample code from the repository and add the following line to Head.rb

alize :wanted_by, :name

Do the following in the console...

matt = Person.create(name: 'Matt')
matt.head = Head.create(size: 1, weight: 2)
ben = Person.create(name: "Ben")
ben.head = Head.create(size: 2, weight: 4)

matt.head.wanted_by << ben


<Head _id: 4fcfa4d1a98972bffc000004, _type: nil, size: 1, weight: 2, person_id: BSON::ObjectId('4fcfa47ba98972bffc000001'), captor_id: nil, wanted_by_ids: [BSON::ObjectId('4fcfa494a98972bffc000002')], wanted_by_fields: []>

A Head was added to the wanted_by relation but the wanted_by_fields array was not updated to reflect this. The wanted_by_ids array has an entry, but the wanted_by_fields does not match.

Thanks again for the work you've done so far.


dzello commented Jun 7, 2012

Thanks @mattjoss for reporting this issue. At a glance, it looks like you're doing the right thing. Let me investigate.


dzello commented Jun 7, 2012

Ok. It looks like some extra work will be needed to support the various add/removal syntax (push, <<, concat, delete, etc). These might not trigger callbacks, or not in the same way. I've added this to the next milestone.

In the meantime, you can do this to get your code working:

ben.wants << matt.head!
matt.head.reload.wanted_by_fields #should now have ben's fields

Not the prettiest, but the gist is that you have to make ben aware of matt's head, then save ben explicitly so he pushes the new fields into matt's head.

@ghost ghost assigned dzello Jun 7, 2012

mattjoss commented Jun 7, 2012

Thanks for the quick response and for the alternate solution. And thanks for sharing your work!


dzello commented Jun 19, 2012

The latest commits (to be released on 0.2.0) will still not get you automatic success with operators like <<, but you will be able to have a much clearer workaround now without relying on the inverse:

matt.head.wanted_by << ben!  # this is that extra call that is needed
matt.wanted_by_fields # should now include ben

The difference is that the denormalize_from callbacks will now fire on the 'matt's head' side. Not yet on <<, but on save. See mongoid_alize_spec near line 184 "should pull data from wanted_by on create" for an example in the specs.

I'm moving this issue to 0.3.0 as I hope to have a good solution for hooking into those methods at that time.


dzello commented Oct 15, 2013

Going to close this and recommend doing direct assignment instead of the << operator.

@dzello dzello closed this Oct 15, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment