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

Caching Eager Loaded Documents

    XMLWordPrintable

    Details

      Description

      We have this code:

      class Band
      include Mongoid::Document
      has_many :albums
      end

      class Album
      include Mongoid::Document
      belongs_to :band
      end

      @bands = Band.includes(:albums).entries

      This is great because now I can run @bands.first.albums without hitting the DB.
      But now, if we write this includes to the rails cache...

      Rails.cache.write('bands', @bands)

      ...we then read the cache.

      bands = Rails.cache.read('bands')

      This returns an array of band documents...

      #<Band _id: 536a53c969702d208f240000, created_at: 2014-05-07 15:39:53 UTC, updated_at: 2014-05-08 15:55:29 UTC, name: "Pink Floyd", fan_count: 394857, #<Band _id: 536adf2a69702d1574130000, created_at: 2014-05-08 01:34:34 UTC, updated_at: 2014-05-08 01:35:40 UTC, name: "Tool", fan_count: 2958394, #<Band _id: 536bcad169702d743e1e0000, created_at: 2014-05-08 18:20:01 UTC, updated_at: 2014-05-08 18:27:10 UTC, name: "My Morning Jacket", fan_count: 3945734

      ...and then we can't get the albums.

      bands.first.albums

      NoMethodError: undefined method 'albums' for #<Array:0x00000104df50c0>

      Is there a special way to cache these eager loaded documents with Rails or Mongoid?

      FYI we're using Mongoid 4.

        Attachments

          Activity

            People

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

              Dates

              Created:
              Updated:
              Resolved: