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

No parent on embedded & scoped first_or_create

    XMLWordPrintable

    Details

    • Type: Task
    • Status: Closed
    • Resolution: Done
    • Affects Version/s: None
    • Fix Version/s: 4.0.0 final
    • Component/s: None
    • Labels:

      Description

      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):

      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):

      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:

      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)

        Attachments

          Activity

            People

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

              Dates

              Created:
              Updated:
              Resolved: