Replies: 3 comments 6 replies
-
Carrying on the discussion with my actual user. I keep going round and round. I get the impression that validation on associated records is only happening when they are loaded, but if the validator always loads them as a matter of course then this will always happen? https://docs.mongodb.com/mongoid/current/tutorials/mongoid-relations/#validations I'm tracing the loading of my association to here. But I don't see why it would load it when it's not necessary. lib/mongoid/validatable.rb
|
Beta Was this translation helpful? Give feedback.
-
Hi @sardjv /@braindeaf, I am looking into this issue and so far I can offer two thoughts:
This sets up a self-referential HABTM association. Have you tested a non-self-referential HABTM association (one with two model classes), or a simpler association like has many? |
Beta Was this translation helpful? Give feedback.
-
Hi @braindeaf , Thank you for adding those cases. I looked at them and as far as I can tell: the association tries to save itself, this causes individual objects to execute the save methods, this causes validations to run but no writes to the database to happen (since no attributes changed). I think this behavior is expected. Because any of the autosaved associations could have been changed in the Does this make sense to you? If not, can you elaborate on what behavior you are expecting? |
Beta Was this translation helpful? Give feedback.
-
I wanted to put it out there that we've discovered a weird and quite frightening set of behaviour whilst upgrading to Mongoid 7.3 w/Rails 5.2 (I know we're working on it) but it also appears to happens in Rails 6.0.
Suppose we have a class
Now from what I can see this is pretty unexciting. I can see that accepts_nested_attributes_for by default sets autosave on the friends association. The behaviour we are seeing that when we save our User, say we're just updating their name every other User is being saved at the same time. I can see that the friends association is being fetched during validation and then consequently since the associated collection is loaded it's being autosaved. So something weird is happening.
I would question at this stage, why we need autosave at all and particularly why it's the default for accepts_nested_attributes.
I know that I take autosaving for granted when using ActiveRecord. My understanding is that you need it to save associations that wouldn't otherwise be saved.
https://docs.mongodb.com/mongoid/current/tutorials/mongoid-relations/#autosaving
If you have a user object and build a new association
When you save user it also saves the associated objects you just built. So this behaviour happens without autosave. Do we need it at all? I thought it was there to automatically save associated object whether or not they are persisted or changed?
Beta Was this translation helpful? Give feedback.
All reactions