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

Reloading associations in callbacks corrupts data

    XMLWordPrintable

    Details

    • Type: Task
    • Status: Closed
    • Resolution: Done
    • Affects Version/s: None
    • Fix Version/s: 2.4.10
    • Component/s: None
    • Labels:

      Description

      I use the mongoid_denormalize plugin, and I noticed that my associations were getting corrupted. I did a bunch of work to pull out the issue out of the plugin, and came up with the repro below using just mongoid (latest gem). Basically, I have two one-to-many relationships to the same class, and in the child class I load the parent relationships in a before_save callback. Then mongoid mixes up the relationships.

      class User
        include Mongoid::Document
       
        field :name, type: String
       
        has_many :edited_posts, class_name: "Post", inverse_of: :editor
        has_many :posts
      end
       
      class Post
        include Mongoid::Document
       
        belongs_to :user
        belongs_to :editor, class_name: "User", inverse_of: :edited_posts
       
        before_save do
          ["editor", "user"].each do |field|
            #this line seems to trigger the issue
            self.send(field, true)
          end
        end
      end
       
      editor = User.create(name: "Editor")
      writer = User.create(name: "Writer")
      post = Post.create(editor: editor, user: writer)
       
      puts post.editor.name #=> Writer, should be Editor
      

      I know it's a bit of a weird scenario, but it's been running amok in my code for a few days, and resulted in a bunch of hair loss. I don't know if it's a bug, some issue in how I've defined the classes, or simply not supported. If it's the last, I need to patch that plugin, which loads the relationship in the callback in order to denormalize fields from the parent side of the relationship into the child side. So any guidance there would helpful.

        Attachments

          Activity

            People

            Assignee:
            Unassigned
            Reporter:
            icambron Isaac Cambron
            Participants:
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Dates

              Created:
              Updated:
              Resolved: