Reputation: 3737
This is my data structure.
Foo
has_many: bar
Bar
belongs_to: Foo
I am trying to write a caching method for Bar that will pull out only "featured" entries.
def self.get_featured
Rails.cache.fetch("featured", :expires_in => 1.day) do
self.where(:featured=>true)
end
end
That works. However, the views which display this data also call for information such as
featured.foo.title
which is not cached as part of the .get_featured method.
Every time I call something like that, the db gets hit again, which happens >40 times per page, thus causing the db to implode a little.
Question, how can I cache filtered Bar AND Foo information for all the filtered records of this Bar?
Upvotes: 0
Views: 189
Reputation: 65857
You can use mongoid includes to eager load the data by specifying the relation names. But currently it is limited to 1 level deep. So i believe it will eager load the foo along with featured, but not sure about the bar. You can try it yourself
def self.get_featured
Rails.cache.fetch("featured", :expires_in => 1.day) do
self.includes(:foo,:bar).where(:featured=>true)
end
end
In order to make it work, the Mongoid identity map must be enabled in the mongoid.yml like this
identity_map_enabled: true
Upvotes: 2