Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-1726

before_create triggers each time validation runs, Should it?

    • Type: Icon: Task Task
    • Resolution: Done
    • 2.4.5
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      None

      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?

            Assignee:
            Unassigned Unassigned
            Reporter:
            eimermusic eimermusic
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: