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

'find' with a block does not work on associations

    • Type: Icon: Bug Bug
    • Resolution: Works as Designed
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 6.0.2, 6.2.1
    • Component/s: None
    • Environment:
      ruby 2.3.1

      The 'find' method on 'has_many' and 'has_and_belongs_to_many' associations always returns 'nil', if called with a block specifying the conditions, like in the example below. The exact same call, using 'find_all' instead, correctly returns an array with appropriate values.

      Example:

      class User
        include Mongoid::Document
        field :email, type: String
        has_and_belongs_to_many :projects
      end
      
      class Project
        include Mongoid::Document
        field :name, type: String
        has_and_belongs_to_many :users
      end
      
      # try to call like this (user is a valid object of class User):
      project = user.projects.find {|p| p.name == "some_name" } # project will always be 'nil'
      
      # however, 'find_all' gives back the expected array
      projects = user.projects.find_all {|p| p.name == "some_name" }
      

      Tested on 6.0.2, but I checked Github for updates on this functionality, but it seems not to be fixed yet for 6.x.x.

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            tischd Daniel Tisch
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: