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

Feature Request: #create_with

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 5.1.0, 6.0.0
    • Affects Version/s: None
    • Component/s: None
    • Labels:

      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.

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            posgarou posgarou
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: