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

Object automatically added to containing object, even if invalid

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

      Consider the following:

      class User
        include Mongoid::Document
      
        embeds_many :accounts
      
      end
      
      class Account
        include Mongoid::Document
      
        embedded_in :user
      
        field :name, :type String
        validates_presence_of :name
      
      end
      
      u = User.find('xxx')
      u.accounts.to_a.count # 0
      a = Account.new(:user => u)
      a.valid? # false
      u.accounts.to_a.count # 1
      
      

      This creates all sorts of headaches when rendering a view which includes the Account instance being altered AND the collection of Account instances (as the new Account object appears in u.accounts).

      I'm pretty sure this doesn't happen with AR as u.accounts would execute a fetch from the DB.

      My only workaround is to run u.reload before retrieving the collection of items.

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

              Created:
              Updated:
              Resolved: