what is the best way to cache database data that doesn't change?
I was caching it in a constant that I set in a file in
config/initializers/ . More concretely, I have a file
config/initializers/db_cache_constants.rb that contains the following
CATEGORIES = Category.find :all
But I have 2 problems:
- If I do a rake db:drop, then rake db:create doesn't work because it
tries to run that file, and it fails because there's no database.
- when from a template I try to get the number of products of one of the
cached categories (a category :has_many products),
<% for category in CATEGORIES %>
<%= category.name %> (<%= category.products.size %>)
<% end %>
it works the first time, but when I reload the page, a NoMethodError
undefined method 'products' for #<Category id: 1, name: "category 1">
Why is this happening?
Both problems are solved if I move the definition of the constant to the
beginning of the app/controllers/application.rb file, just before the
definition of the ApplicationController class, but...
is there a better place to do this type of caching?
Thanks in advance.