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

_id does not get updated for custom key , if key attribute gets updated

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

      observed in mongoid 2.0.2: sorry for the lengthy code..

      Scenario:

      when I have a custom key, let's say the attribute :ident , and by accident there was a duplicate key,
      so validation doesn't succeed, and the container / parent can't be saved ...

      Possible Bug:

      when you try to update the 'key attribute' , e.g. :ident of an instance, then the _id attribute does not get updated!
      e.g. it does not follow the value of the newly updated key attribute. That looks like a bug to me...
      How else could you fix validation problems? You'd have to update both item.id and item.ident?? not what I would expect...

      class Container
        include Mongoid::Document
        embeds_many :items
        validates_associated :items
      end
      
      class Item
        include Mongoid::Document
        embedded_in :container
        field :ident
        key   :ident
        validates_presence_of :ident
        validate :uniqueness_here_of_ident , :on => :update
      
      
      private                                                                              
        def uniqueness_here_of_ident
          h = {} ; n = 0
          container.items.each do |i| # check the parent object's items..                     
            h[i[:ident]] ||= 0
            h[i[:ident]] += 1
            n += 1
          end
          errors.add :ident , ":ident must be unique within the parent object" if h.keys.size != n
        end
      end
      
      
      c = Container.create
      
      
      c.items << Item.new(:ident => "one")
       => [#<Item _id: one, _type: nil, _id: "one", ident: "one", data: nil>] 
      c.items.last.valid?
       => true
      
      c.items << Item.new(:ident => "one")
      => [#<Item _id: one, _type: nil, _id: "one", ident: "one", data: nil>] 
      c.items.last.vaild?
       => false
      
      c.items.first == c.items.last
       => true 
      
      c.items.last.ident = "two"   <-- trying to fix the incorrect key attribute value
       => "two"
      
      c.items.last
       => #<Item _id: one, _type: nil, _id: "one", ident: "two", data: nil>   <-- but _id does not follow the value of :ident !!
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            tilo Tilo S
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: