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

#create_with parameters are included into search criteria when calling find_or_create_by

    • Type: Icon: Bug Bug
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 7.0.4
    • Component/s: None
    • None

      When calling #find_or_create_by after #create_with, criteria from both methods are used to find a record.

       

      Company.create_with(name: 'My Company 1').find_or_create_by(number: '123')
      => #<Company _id: 5d0516627ba3cbb9e8a2ef86, created_at: 2019-06-15 16:01:38 UTC, updated_at: 2019-06-15 16:01:38 UTC, name: "My Company 1", number: "123"> 
      
      Company.create_with(name: 'My Company 2').find_or_create_by(number: '123')
      => #<Company _id: 5d0516687ba3cbb9e8a2ef87, created_at: 2019-06-15 16:01:44 UTC, updated_at: 2019-06-15 16:01:44 UTC, name: "My Company 2", number: "123"> 
      
      Company.all.to_a
      => [#<Company _id: 5d0516627ba3cbb9e8a2ef86, created_at: 2019-06-15 16:01:38 UTC, updated_at: 2019-06-15 16:01:38 UTC, name: "My Company 1", number: "123">, #<Company _id: 5d0516687ba3cbb9e8a2ef87, created_at: 2019-06-15 16:01:44 UTC, updated_at: 2019-06-15 16:01:44 UTC, name: "My Company 2", number: "123">]
      

      So second call to #find_or_create_by searches for a Company by both name and number.

       

      Expected behavior - only criteria in #find_or_create_by is used to search for an existing record.
      The output should look something like this

      company_1 = Company.create_with(name: 'My Company 1').find_or_create_by(number: '123') 
      => #<Company _id: 5d0516627ba3cbb9e8a2ef86, created_at: 2019-06-15 16:01:38 UTC, updated_at: 2019-06-15 16:01:38 UTC, name: "My Company 1", number: "123"> 
      
      company_2 = Company.create_with(name: 'My Company 2').find_or_create_by(number: '123') 
      => #<Company _id: 5d0516627ba3cbb9e8a2ef86, created_at: 2019-06-15 16:01:38 UTC, updated_at: 2019-06-15 16:01:38 UTC, name: "My Company 1", number: "123"> 
      
      company_1 == company_2 
      => true 
      
      Company.all.to_a 
      => [#<Company _id: 5d0516627ba3cbb9e8a2ef86, created_at: 2019-06-15 16:01:38 UTC, updated_at: 2019-06-15 16:01:38 UTC, name: "My Company 1", number: "123">]
      

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            a.nikolaiev Andrii Nikolaiev
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: