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

Access to parent from embedded document on creation (Mongoid)

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

      This trick works with "has_many" relation, but fails with "embeds_many". Any ideas?

          
          class Country
              include Mongoid::Document
      
              field :name, type: String
              embeds_many :cities  
          end
      
          class City
              include Mongoid::Document
      
              field :name, type: String
              field :full_name, type: String, default: ->{ "#{name}, #{country.name}" }
              embedded_in :country
          end
      

      1.9.3p392 :025 > c = Country.find_or_create_by(name: 'foo')
      => #<Country _id: foo, name: "foo">

      1.9.3p392 :026 > c.cities.find_or_create_by(name: 'bar')
      NoMethodError: undefined method `city' for nil:NilClass

      So, it fails on a line "field :full_name, type: String, default: ->{ "#

      {name}

      , #

      {country.name}

      " }" becouse country is undefined for that moment

            Assignee:
            Unassigned Unassigned
            Reporter:
            WizeFlux Andrew [X]
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: