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

Using concat on has_and_belongs_to_many ids default value is not working the first time

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 8.0.1
    • Affects Version/s: 7.3.1
    • Component/s: Associations, Attributes
    • None
    • Minor Change

       

      Hello,

      After rubocop complained, a += operator was replaced by concat on some has_and_belongs_to_many id fields.

      And concat didn't work as expected.

       

      How to reproduce :

      class Blog
        include Mongoid::Document
        include Mongoid::Timestamps
        
        has_and_belongs_to_many :authors, inverse_of: nil
      end
      
      class Author
        include Mongoid::Document
        include Mongoid::Timestamps
      
        field :name, type: String
      end
      
      author = Author.create!(name: 'me')
      Blog.create!
      
      Blog.all.each do |blog|
        blog.author_ids.concat(Array(author.id))
        puts "first time : #{blog.author_ids}"
      
        blog.author_ids.concat(Array(author.id))
        puts "second time : #{blog.author_ids}"
      end

      Output :

       

       

      first time : []
      second time : [BSON::ObjectId('6278f1769d1fa2ff46467c48')]
      

       

       

      So as author_ids is nil on the blog instance, the default value returned is an empty array.

      The first time I try to concatenate something with author_ids, it seems that I finally concatenate it with the default value empty array that is not associated to the blog instance author_ids field, so author_ids is still empty.

      Then, the array returned by author_ids is ok and concat will work as expected.

       

      Note :

      Using += instead of concat fixed my issue.

      Any call to blog.author_ids before concat also fix the issue.

            Assignee:
            neil.shweky@mongodb.com Neil Shweky (Inactive)
            Reporter:
            ivan.maireaux@eventmaker.io Ivan Maireaux
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: