K
K
Kukunin2013-08-08 18:39:31
Ruby on Rails
Kukunin, 2013-08-08 18:39:31

Cache in Ruby on Rails

Good afternoon. I am currently optimizing one project, due to the increased load. In this regard, I am studying various cache methods in rails, and not only. And I have some questions.

Rails 3 had three types of cache - page, action and fragment. Page - the fastest - we generate html and give it to some nginx. But, the least flexible.
In Rails 4, the first two were canceled, finished and only fragment was left. I think smart guys made such a decision, and they had their own reasons.

So I wanted to know how much the fragment cache is slower in speed compared to the page? Something I did not find comparisons.

Well, the most important question: let's say we only have a fragment cache left (and it is in Rails 4). It caches the view, but, as common sense suggests, you need to cache queries in the database (since they load the server the most), and overtaking from erb to html is a relatively fast operation. It turns out that in order to cache queries in the database, they need to be transferred to the view, inside the cache do end block?

It was:

<% @articles.each do %>
  here is the markup
<% end %>

It became:

<% cache do %>
  <% Article.find_each do %>
  here is the markup
  <% end %>
<% end %>


Notice how the logic moved from the controller to the view?

Either I misunderstood something, and here magic is used that caches queries in the database too, or you need to put up with this (well, or transfer methods to helpers that would return models from the database).

Tell me please. Any info on caching in rails would be helpful.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
alex_bel, 2013-08-08
@alex_bel

fragment сache is, in principle, slower than page for the reason that the rail server does not even twitch with page. Only the web server works. This is a super fast answer, but also the least flexible as you rightly said.
Rails caches all queries to the database.
@articles = Article.where(...)
those. here, when you re-access the result of this request will be taken from the cache.

Z
Zelgadis, 2013-08-08
@Zelgadis

I don’t know about you, but my request to the database is ~ 2ms, and the view is rendered ~ 20-40ms (haml), with the cache the page is rendered in ~ 2 ms (a request to the database and html is immediately returned).
And alex_bel is right - requests to the database are cached.

A
Adil1, 2013-11-26
@Adil1

http://habrahabr.ru/post/165355/ did you not get acquainted with this? :) very useful info for me

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question