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

Allow embeds_one to accept a class as a second argument to build

    • Type: Icon: Improvement Improvement
    • Resolution: Unresolved
    • Priority: Icon: Unknown Unknown
    • 9.1.0
    • Affects Version/s: None
    • Component/s: Associations
    • None
    • Ruby Drivers

      For example:

      # Shows the discrepancy between the `embeds_one` & `embeds_many` build API:
      #
      # - `embeds_many` accepts a class as a second argument on `build`
      # - `embeds_one` does not
      #
      # After some experimentation, you can work around this with `_type` in the attrs,
      # but I would expect the build API to be consistent between the two
      # 
      # Issue exists in upstream v6, v7, v8
      class BatchOperation
        include Mongoid::Document
      
        embeds_one :fetcher
        embeds_many :fetchers
      end
      
      class Fetcher
        include Mongoid::Document
        embedded_in :batch_operation
      end
      
      class FileFetcher < Fetcher
      end
      
      class PageFetcher < Fetcher
      end
      
      BatchOperation.collection.drop
      
      operation = BatchOperation.create
      operation.build_fetcher({}, FileFetcher)
      operation.fetchers.build({}, PageFetcher)
      # Expected: [ FileFetcher, PageFetcher ]
      # Upstream: [ Fetcher, PageFetcher ]
      pp [operation.fetcher.class, operation.fetchers[0].class]
      
      # This saves immediately so isn't suitable:
      # operation.fetcher = FileFetcher.new
      
      # This can work, but is inconsistent with the embeds_many API
      # operation.build_fetcher(_type: "FileFetcher")
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            alex.bevilacqua@mongodb.com Alex Bevilacqua
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: