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

Feature Request: #create_with

    XMLWordPrintable

    Details

    • Type: Task
    • Status: Closed
    • Priority: Major - P3
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 5.1.0, 6.0.0
    • Component/s: None
    • Labels:
    • Sprint:
      Ruby Sprint 29, Ruby Sprint 34

      Description

      In ActiveRecord, the #create_with method is extremely useful in conjunction with #find_or_create_by. Example:

      Foo.create_with(phone_number: api_obj.phone_number).find_or_create_by(name: api_obj.name)
      

      Currently, as I understand it, the only way to implement this in Mongoid is to pass a block (which you can also do in AR, of course).

      Foo.find_or_create_by(name: api_obj.name) { |foo| foo.phone_number = api_obj.phone_number }
      

      It would be great if #create_with were supported. Two reasons:

      1. It's more readable. Nothing in the block syntax tells you that the block is only executed if the object is created and not if it is found already existing; in fact, there's every reason for those unfamiliar with the details of #find_or_create_by to assume that the block is always executed. The #create_with syntax makes it clearer what is executed when.
      2. This would further ease transition from ActiveRecord.

        Attachments

          Issue Links

            Activity

              People

              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: