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

after_add event fired when document is loaded from database

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 5.1.0
    • Affects Version/s: None
    • Component/s: None
    • None

      This may be a misunderstanding on my part, so please forgive me if I've made an incorrect assumption. When I'm using the after_add event to do some housekeeping on document relationships it correctly fires when a document is added to the collection via push or create. However it is also fired when again when reloading a child document and accessing the parent association which I didn't expect and it's causing duplicate housekeeping work.

      Let me give an example

      class Category
      include Mongoid::Document

      belongs_to :parent_category, class_name: "Category"
      has_many :child_categories, class_name: "Category", after_add: :child_category_added

      def child_category_added(child)
      puts "#

      {child}

      was added"
      end

      end

      it "should not fire after_add when reloading" do
      parent = Category.create()
      child = parent.child_categories.create!

      Category.any_instance.should_not_receive(:child_category_added)
      child.reload.parent_category
      end

      If this is the intended behavior then is there a way to detect that it's due to a reload and not because of an actual change to the association?

      I'm using current HEAD revision 164755a9d038e00faaffc054894c3390d17b1345

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

              Created:
              Updated:
              Resolved: