Rails Caching in Agile Web Development w/ Rails4 - ruby-on-rails

I'm working my way through the book Agile Web Development with Rails4, and I just read the (first) part about caching parts of a view to avoid overwhelming the database.
I've of course set the caching option to true in the config for the development environment.
The problem is that caching doesn't seem to be working.
Here is my app/views/store/index.html.erb file, exactly like the one given in the book, to enable caching :
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<h1>Your Pragmatic Catalog</h1>
<% cache ['store', Product.latest] do %>
<% #products.each do |product| %>
<% cache ['entry', product] do %>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line">
<span class="price"><%= number_to_currency(product.price) %></span>
</div>
</div>
<% end %>
<% end %>
<% end %>
And here is the rails server log, clearly showing that the databse was accessed multiple times (although a line mentions caching) : http://pastebin.com/v2jGiHKL
Here is my app/views/store/index.html.erb file, where I tried something else for caching :
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<h1>Your Pragmatic Catalog</h1>
<% cache('caching') do %>
<% #products.each do |product| %>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line">
<span class="price"><%= number_to_currency(product.price) %></span>
</div>
</div>
<% end %>
<% end %>
And here is the corresponding log, showing that caching was successful (as the database was not queried) : http://pastebin.com/ZTk9A9RA
Can someone explain why one seems to work and not the other, or how the first one should work ? Thank you :)
Note that in the book, it says that with caching enabled, reloading the store page shouldn't show new parts of the store/index.html.erb if the changes were made inside a cached block ; yet it does in both case. Any idea ?

The parameter you pass to the cache api is the caching key. The hashing function of that key is where the cached fragment will be stored, and where it will be looked for.
In your code (cache('caching')) the caching key is hard-coded, and never changes, so, unless the cache is invalidated (either manually in your code, or when its TTL has passed) - the same fragment will be sent to the client.
In the code from the book (cache ['store', Product.latest]) the key depends on the latest product. This means that if the latest product changes (another product was added, or updated) - the next call will automatically 'know' not to take the page from the cache, but to recreate the cache.
What is shown in the logs:
[1m[35mProduct Load (0.3ms)[0m SELECT "products".* FROM "products" ORDER BY "products"."updated_at" DESC LIMIT 1
Is actually the result of Product.latest, not of Product.all.
To sum up - both code fragments are cached, but in the example code, there is a (small) hit to the database to verify the validity of the cache, whether the page was cached or not.
If you are invalidating the cache yourself, you can keep the hard-coded version of the code, but if not, you better think of an invalidation scheme, whether it is like the example code suggests or something else.

Related

Rails HTML Multi Layered IF checking

I am working on a layout that requires a couple of checks to the database, but I cannot figure out the logic on the IF statement. I have a People table where each record holds a Position field. There are times that specific positions will be held by two people. In which cases they want to be Co-Position. So I current am listing said Position on my page with:
<li>
<% #people.each do |person| %>
<% if person.position == 'Office1' %>
<div class="image">
<%= link_to(person_path) do %>
<%= image_tag("profiles/#{person.uname}S.jpg") %>
<% end %>
</div>
<div class="body2">
<h4>Office</h4>
<%= link_to(person_path) do %>
<h5><%= person.fname %> <%= person.lname %></h5>
<% end %>
</div>
<% end %>
<% end %>
</li>
Now within that I need to run a check at <h4>Office</h4> to see if another record holds Office2, but if I place an IF statement around the H4 tags will it be checking the already fetched record or will it check the entirety of the Person database? Do I need to do this check first and then do an IF/Then or can this be done in a more streamlined way?
Basically I need to check if Office2 is present somewhere in the Position field, and if it is I need the H4 to read Co-Office, else I need it to read Office.
If your condition is if person.position.include?('Office2') then no, it won't touch the database again. The person object is loaded with all its attributes.

How to increase a simple counter

This is my home.html.erb:
<div class="container">
<% #articles.each do |article| %>
<div class="bloc-article">
<div class="article">
<%= image_tag(article.picture, alt: "Article", width:"230", height:"240")%>
<div class="align-content-column">
<div class="celsuis"><span class="moins">- </span> <%= article.counter %>° <span class="plus">+</span></div>
<div class="title">
<%= article.title %>
</div>
<h2><%= article.price %> €</h2>
<div class="desc-author">
<p><%= article.description[0, 200] %>....</p>
<div class="author-deal">
<h3><%= article.author %></h3>
<div class="alert alert-info"><%= link_to "Voir le Deal", article_path(article) %></div>
</div>
</div>
</div>
</div>
</div>
<% end %>
</div>
I have a span - and a span +. I want put an onClick method to increase for + and decrease for -.
To do that I have a database with article.counter (auto-generate number with Faker::numb)
With Vue.js I can do that easily, but on Ruby on Rails I am totaly lost.
You have lots of serious issues about understanding Rails applications (and web applications in general). Here are some hints:
All Ruby code (including those snippets inside <% %>) is evaluated on the server.
All JavaScript code in a Rails application is evaluated on the browsers.
The server and the browsers are different computers, so they don't share memory and thus objects.
A browser can't call Ruby methods as the Ruby code can only be evaluated on the server. A browser can only ask the server to do something via sending HTTP requests.
When a request is finished and the web page is shown on the browser, the server knows the browser no more, and every bit of memory on the server that's associated with the request becomes garbage.
Let's say you have a Model "Article" with a column "quantity". You could do something in the lines of this (I haven't tested it, just giving you a guideline)
As long as you use the normal resources in your routes:
In your view:
<%= form_for (#article), method: :put do |f| %>
<%= f.button "-", name: "update", value: "decrement" %>
<%= f.button "+", name: "update", value: "increment" %>
<% end %>
In your controller:
def update
#article = Article.find(whatever you use to find it)
if params[:update]["increment"]
#article.quantity += 1
elsif params[:update]["decrement"]
#article.quantity -= 1
end
# repond_to here and so on
# and don't forget to #article.save
end
You could then use jQuery (probably no need for an onClick event) to render the part where you show the count in the view.

Rails partial caching is showing view changes despite no model changes

Following the guide from "Agile Web Development with Rails 4."
It covers caching for a product catalog to only re-render products that changed.
I edited (config/environments/development.rb):
config.action_controller.perform_caching = true
Added code to return most recently updated product:
(app/models/product.rb)
def self.latest
Product.order(:updated_at).latest
end
Lastly updated the store index for the cache:
(app/views/store/index.html.erb)
<h1>Your Pragmatic Catalog</h1>
<% cache ['store', Product.latest] do %>
<% #products.each do |product| %>
<% cache ['entry', product] do %>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line">
<span class="price"><%= number_to_currency(product.price) %></span>
</div>
</div>
<% end %>
<% end %>
<% end %>
The book states the only way to test if caching is working is to change the view so all I did was add some lorem ipsum within one or both cache tags but the browser immediately shows the change on refresh... Frustrating! Any clue?
Your cache key for the collection is not changing. That happens because cache ['store', Product.latest] is not as clever as you expect. If you have a look at the log you'll see that the cache key that was used is a literal including something like ActiveRecord::Relation::Products.
Use the last updated_at value cache ['store', Product.latest.max(:updated_at)] for better results.
In Rails 5 this will be easier due to the addition of cache_key to ActiveRecord::Relation a few weeks ago.
try using
<% cache ['v1', Product.order(updated_at: :desc).last] do %>
instead of
<% cache ['store', Product.latest] do %>

How to tell if Caching is working. Rails 4

I am following along with the 'Agile Web Development with Rails 4' guide and have come to a section on caching. Here are the steps to follow:
in config/environments/development.rb
config.action_controller.perform_caching = true
In app/models/product.rb
def self.latest
Product.order(:updated_at).last
end
in views/store/index.html.erb
<% cache ['store', Product.latest] do %>
<% #products.each do |product| %>
<% cache ['entry', product] do %>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line">
<span class="price"><%= number_to_currency(product.price) %></span>
</div>
</div>
<% end %>
<% end %>
<% end %>
To verify the cash is working, the book says: "As far as verifying that this works, unfortunately there isn't much to see. If you go to that page, you should see nothing change, which in fact is the point! The best you can do is to make a change to the template anywhere inside the cache block without updating any product and verifying that you do not see that update because the cached version of the page has not been updated".
However, when I try and add a "Hello" string in the code within the cache blocks, it appears on the page. I've done all the server restarting and what not.
But, when I reload the page on my local host I do see this line
Cache digest for app/views/store/index.html.erb: 6c620ede1d4e824439a7b0e3b177620f
which is not their when I have
config.action_controller.perform_caching = false
Link to git hub repo: https://github.com/BrianLobdell/depot
Thank you,
Brian
Rails updates the cache when changing the file, so it's easier to manipulate the cache instead.
You can retrieve the cache fragment using the cache digest for the page in your Rails console (the digest might have changed, make sure to use the recent one!):
key = ['store', Product.latest, '6c620ede1d4e824439a7b0e3b177620f']
ActionController::Base.new.read_fragment(key)
This should return the cached fragment. To ensure that Ruby actually hits the cache when serving the page, you could replace the fragment with some other content:
ActionController::Base.new.write_fragment(key, 'it works!')
Reload the page, you should see "it works!".

Caching doesn't work Rails 4.0

I'm following the 'Agile Web Development with Rails 4' book and I'm stuck at page 105 about the caching.
I have the following code in index.html.erb
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<h1>Your Pragmatic Catalog</h1>
<% cache ['store', Product.latest] do %>
<% #products.each do |product| %>
<% cache ['entry', product] do %>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line">
<span class="price"><%= number_to_currency(product.price) %></span>
</div>
</div>
<% end %>
<% end %>
<% end %>
The first doubt is the following:
1) What does cache ['store', Product.latest] exactly do? It creates a cache, available from all StoreController actions, named "store" and associates the cache with the Product.latest: why should I do the last thing? Why do I need to associate my cache to a Product.latest?
Always at the same page the book says: "As far as verifying that this works, unfortunately there isn't much to see. If you go to that page, you should see nothing change, which in fact is the point! The best you can do is to make a change to the template anywhere inside the cache block without updating any product and verifying that you do not see that update because the cached version of the page has not been updated".
So I tried something like this:
<% cache ['store', Product.latest] do %>
"hello"
........
........
<% end %>
But I still get this update, the page shows me the "hello" string, why is it so? Shouldn't I see it?
P.S. Obviously I edited my config/environments/development.rb and restarted the server
Start your application on production mode and you will see that caching works.
What did you edited in development.rb? Please compare it to production.rb and copy-paste all caching configuration properties.
I had the same "problem", and I think what the book is saying is not correct. As far as I can tell, the reason why you see the changes on the website, even though caching is active, is that Rails 4 uses cache digests. For more information, check out:
http://blog.remarkablelabs.com/2012/12/russian-doll-caching-cache-digests-rails-4-countdown-to-2013
When you changed config.cache_classes to false, you just told Rails to not automatically regenerate views with each request. That's why you stopped seeing changes, it's not because "caching" was working correctly.

Resources