mongoid/mongoid — Issue #1725: before_create triggers each time validation runs, Should it?
Author: eimermusic
Created: 2012-02-16 12:12:39+00:00
State: open

I found this strange so I wanted to check if this is really intended behavior.

When I save a "tree" of associated objects (has_many and belongs_to linked) I see a lot of queries re-running the uniqueness validation of one of the models whenever I save and update the patent models.

E.G.
Company has_many Department(s)
Department has_many Employee(s)
Company (also) has_many Employee(s)
...and also the reverse belongs_to associations.
Employee validates the uniqueness of the social security number.

When saving (updating) company or department I see the Employee validation run the uniqueness query. Why would it do that? There is nothing stored in those collections that relates to the Employee. All the foreign keys are in the Employee collection.

I noticed another related thing when playing around the the order of events in my code. I tried using before_create to assign the belongs_to "parent" to the employee before inserting it. But since the validations ran multiple times my before_create also ran multiple times causing a nice loop.

AFAICT: Validations run multiple times in some circumstances. before_create also run multiple times (each time validations run?)
This doesn't agree with how I read the docs. That is why I raise this question.

Am I making sense? How can I clarify myself?