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

Saving unrelated model in observers after_save creates extra record on wrong model

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

      Given these models and observer:

      class Project
        include Mongoid::Document
      
        field :title
      
        has_many :tasks, :dependent => :destroy
      
        accepts_nested_attributes_for :tasks, :allow_destroy => true
      end
      
      class Task
        include Mongoid::Document
      
        field :title
      
        belongs_to :project
      end
      
      class Log
        include Mongoid::Document
      
        field :message
      end
      
      class TaskObserver < Mongoid::Observer
        def after_save(task)
          Log.create!(:message => "Task created")
        end
      end
      

      Console (with 100% empty db):

      >> p = Project.create!
      >> p.tasks_attributes = [{:title => "My Task"}]
      [
          [0] {
              :title => "My Task"
          }
      ]
      
      >> Project.first.tasks.to_a
      [
          [0] #<Task _id: 4ed61a11662e0c7ad400000d, title: "My Task", project_id: BSON::ObjectId('4ed6199a662e0c7ad4000007'), _type: nil>,
          [1] #<Task _id: 4ed62243662e0c7fc8000023, title: nil, project_id: nil, _type: nil, message: "Task created">
      ]
      
      >> Log.all.to_a
      []
      

      As can be seen an extra Task record with the :message field and no Log records has been created.

      ruby 1.8.7p352 - mongoid 2.3.4 - rails 3.1.1

            Assignee:
            Unassigned Unassigned
            Reporter:
            wulffeld Martin Moen Wulffeld
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: