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

No parent on embedded & scoped first_or_create

    • Type: Icon: Task Task
    • Resolution: Done
    • 4.0.0 final
    • Affects Version/s: None
    • Component/s: None

      When calling first_or_create on a scoped embedded collection, the parent is not set:

      Here are simplified versions of my models (original ones are namespaced, with class_name: in relations):

      Unable to find source-code formatter for language: `ruby. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
      class User
        include Mongoid::Document
        embeds_many :api_keys, inverse_of: :user
        field :email, type: String
      end
      
      class ApiKey
        include Mongoid::Document
        embedded_in :user, inverse_of: :api_keys
        field :type,  type: Symbol
        field :token, type: String
        scope :session, -> { where(type: :session) }
        scope :api,     -> { where(type: :api) }
      end
      

      `

      In the console (User doesn't contain any api key yet):

      Unable to find source-code formatter for language: `ruby. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
      u=User.first
      
      k=u.api_keys.first_or_create
      k.user.present?
      => true
      
      k=u.api_keys.session.first_or_create
      k.user.present?
      => false
      k.type
      => :session
      k.save
      Mongoid::Errors::NoParent:
      Problem:
        Cannot persist embedded document ApiKey without a parent document.
      [...]
      

      `
      Using the following code works but it's not very clean:

      Unable to find source-code formatter for language: `ruby. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
      k=u.api_keys.session.first_or_create(user: u)
      

      `
      The parent is automatically set with a referenced relation (has_many/belongs_to)

      Versions: Rails 4.0.0 / Mongoid master (5a34921251b6d159b6ef3aa2a9f9aebdc6ac687f at the time of writing)

            Assignee:
            durran Durran Jordan
            Reporter:
            gauthier-delacroix gauthier-delacroix
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: