Ruby on Rails - Caching Variables

I have these two variables set in the controller. How to cache them so that they do not contact the database every time, only for the first time.

@tablenutrients = Nutrient.find(:all) @columnnutrients = @tablenutrients.collect {|x| x.nutrient} 
+4
source share
3 answers

what @djlumley said.

In general, you can also configure and use ActiveSupport :: Cache :: Store to explicitly store your own variables. Then you can get / set cached values, for example as follows:

 @tablenutrients = Rails.cache.fetch("tablenutrients") do Nutrient.find(:all) end 
+10
source

If your database is configured correctly, it should cache your data by default. If you use MySQL or postgresql, you can change the amoutn RAM used by the cache to provide a high level of cache hit.

Besides simple database caching, using Dalli to connect to memcached should significantly improve performance.

Rails should use memcached to cache all of your active memcached write requests, provided it is configured correctly. The Rails tutorial on caching along with the Dalli documentation should help you get started with the version of Rails you are working with.

+3
source

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.

+2
source

Source: https://habr.com/ru/post/1437709/


All Articles