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

Arrays attributes don't update

    • Type: Icon: Improvement Improvement
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: Attributes
    • None
    • 4

      What is the mistake in this code for not be able to update an array within a document?
      Model

      class Foo
        include Mongoid::Document
        include Mongoid::Timestamps::Created
      
        field :myarray, type: Array
      
      end
      

      Controller

      def add_item
              @foo= Foo.find_by(uuid: params[:uuid])
              unless @foo.nil?
                  unless @foo.has_attribute? :myarray
                      @foo[:myarray] = Array.new
                  end
                  @foo[:myarray] << params[:item]
                  @foo.save
              end
      end
      

      I am using Rails 4 with MongoId 4 and if I do {{ p @foo }} before {{ @foo.save }} I can see @foo correctly changed but for any reason the update is not persisted.

      Otherwise if I change {{ @foo[:myarray] << params[:item] }} by {{ @foo[:myarray] += [ params[:item] ] }} then all works fine.

      I'm missing something in the first way?

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            Vrael Vrael [X]
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: