Rails has several built-in caching options for you, two of which are likely to work for you, depending on what you do with the query result:
Fragment Caching
If you used this as a collection for the selection box of a frequently used form, I would go with this option. This will allow you to cache not only the database result, but also the actual HTML section on the page. This is done simply by throwing <%= cache do %> around the partition, for example:
<html> ... <body> ... <div class='content'> ... <%= cache do %> <%= select "nutrient", "nutrient", Nutrient.all.collect(&:nutrient) } %> <% end %>
Rail.cache
You can also write a method to talk directly to the built-in cache repository by dropping the method in the ApplicationController and then run it in the before_filter callback, like this:
application_controller.rb
class ApplicationController < ActionController::Base before_filter :retrieve_nutrients def retrieve_nutrients @nutrients = Rails.cache.fetch("nutrients") do Nutrient.all.collect(&:nutrient) end end end
In both cases, in a production environment, you will want to configure either Memcached or Redis to act as a caching layer (they are behind Rails.cache and can be implemented). I would check out the Rails Guides for a deeper look.
source share