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

Create callback being called before save! and update callback is fired immediately afterwards

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Minor - P4 Minor - P4
    • None
    • Affects Version/s: 4.0.0 final
    • Component/s: Associations, Callbacks
    • None

      class Project
        include Mongoid::Document
        has_and_belongs_to_many :users 
        field :name, type: String
        after_create :create_callback
        after_update :update_callback
      
        def create_callback
           Project.skip_callback(:update, :after, :update_callback)
           puts "Create callback called"
           Project.set_callback(:update, :after, :update_callback)
        end
      
        def update_callback
           puts "Update callback called"
        end
      end

      Here is the controller:

      project = Project.new(name: "Project1")
      puts "new project"
       
      if project.valid?
        project.users << current_user
        puts "added authenticated user"
        project.save!
        puts "saved project"
      end

      This is the output:

      new project
      added authenticated user
      Create callback called
      Update callback called
      saved project

      There are two of oddities I'm seeing:

      1. Append one or many tags, saving them if the person is persisted.
        person.tags << Tag.new

      So, in my code I appended the authenticated user to a newly (not-persisted) project. I expected the project to call the after_create callback after project.save!, but it seems like it is called after I append the user. This seems contrary to what the docs say, since the project was not persisted and so the appending the user should not fire the after_create callback?

      • The after_update callback is being called immediately after the after_create callback. Is this expected behavior?

            Assignee:
            neil.shweky@mongodb.com Neil Shweky (Inactive)
            Reporter:
            marblemass marblemass
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: