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

Caching of stale has_many relations

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

      I'm using Mongoid 3.0.14, Moped 1.3.1, ruby-1.9.3-p392 on OS X – Lion.

      When you have a has_many relationship and you find a child record and update it, when should the parent be updated in memory? Or is it never updated? I didn't find docs on this subject and the behavior didn't match my expectations.

      Sample code:

      Mongoid::Threaded.disable_identity_map(:all)  # rule out identity map
      class Band
          include Mongoid::Document
          has_many :artists, autosave: true, validate: true, dependent: :destroy
          field :name, type: String
      end
      
      class Artist
          include Mongoid::Document
          belongs_to :band
          field :name, type: String
          field :age, type: Integer
      end
      
      Band.destroy_all
      Artist.destroy_all
      
      band = Band.new(name: "Beatles")
      artist = band.artists.find_or_initialize_by(name: "John", age: 24)
      band.save
      artist.save
      
      band.artists.first.age MONGOID-27 - correct
      artist = band.artists.find_or_initialize_by(name: "John")
      artist.age = 25
      band.artists.first.age MONGOID-27 - correct, not yet persisted
      artist.save
      
      band.artists.first.age MONGOID-27 - incorrect, db now has 25 but traversing from parent yields stale data
      band.artists(true).first.age MONGOID-28 – works as expected after reload
      
      

      By digging into the mongoid code I see that the way the getter is defined it will always return a stale artist reference unless an explicit reload is called. Is my understanding correct? Is that the expected behavior?

            Assignee:
            Unassigned Unassigned
            Reporter:
            abhirao abhirao
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: