Ruby on Rails Wednesday, March 28, 2018

> On Mar 28, 2018, at 11:11 AM, David McDonald <daveomcd@gmail.com> wrote:
>
> 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

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/3A531736-9D66-4EBE-9775-577E79EDAD87%40wdstudio.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment