Mongoid: caching uploaded documents

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.albumswithout getting into the database. But now, if we write, this includes cache rails ...

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

... then we read the cache.

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

This returns an array of tape 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 cannot get the albums.

bands.first.albums

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

Is there a way to cache these downloaded documents using Rails or Mongoid?

FYI we use Mongoid 4.

+4
source share
1 answer
+4

Source: https://habr.com/ru/post/1540394/


All Articles