Is there a different approach I should take on active queries I execute that don't change often?

As I’m going through my project I’m looking at places in my application that are causing pages to load longer than perhaps they should. I’m finding some queries that execute for my page navigation that happen each time a page reloads, but their information that is returned doesn’t usually change. An example I have would be I display 32 NFL Club logos that serve as links to each clubs page in my navigation. The query looks like this:

SELECT [clubs].* FROM [clubs] WHERE (clubs.is_disabled = 0) ORDER BY [clubs].[city] ASC;



Now this code runs in development and it's saying it takes 32.9ms to execute. But to my point these 32 clubs rarely change. Is there a different approach I should be taking to this other than having it run on every page request? Thanks!

You could "memoize" it in a class method, so it runs only once per application start. Take advantage of the fact that Rails is a long-running process.

# in club model

def self.nfl_logos   @nfl_logos ||= where(is_disabled: false).order(city: :asc) end

Then refer to this as Club.nfl_logos in your controller or view, wherever you build this page element. It will only ever run once (per server instance/thread) and thereafter always return from the cached instance.

Another thing to remember is Turbolinks. You are using it, right? Elements like this that rarely change can be marked out as persistent between reloads, so they will be cached by the browser and never re-requested. Assuming your layout is properly divided into areas that change and areas that do not, this could take care of this problem for you as well.

Walter