Caching doesn't work Rails 4.0 - ruby-on-rails

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.

Related

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!".

Combining two associations in my "each do" loop method

I'm a little new to back-end programming...I'm currently running the following code in my rails 4 app to show a basic list of all the admins on a project (if there are any)...
<% if project.projectadmins.any? %>
<div class="row-fluid">
<% project.projectadmins.each do |user| %>
<div class="collaborator">
<%= link_to user do %>
<%= image_tag user.image_url(:thumb).to_s, :class => "profile-pic-thumb" %>
<% end %>
</div>
<% end %>
</div>
<% end %>
However, I also have projectcollaborators for each project, so I'd like to know what the most effective way would be to combine those and provide a list of both projectadmins AND projectcollaborators (with project admins being listed first if there are any...other than that ordering is not important).
I assume the if statement at the beginning would change to...
<% if project.projectadmins.any? || project.projectcollaborators.any? %>
but I'm not 100% sure and am lost on the rest...any help is much appreciated.
You could create a scope, for example project_admins_and_collaborators, which gets all the needed records and then use it in your loop.
You can also do this in following way
project_admins_and_collaborators = project.projectadmins
project_admins_and_collaborators << project.projectcollaborators
project_admins_and_collaborators.flatten.uniq do |user|
#your code
end

Rails Caching in Agile Web Development w/ Rails4

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.

Page not working on Heroku

I made an app in RoR and it's working perfectly locally, but there's only one page that's not working when I upload to Heroku. It's a view that has only this in the code:
<h1>Listagem</h1>
<% #items.each do |item| %>
<%= link_to item.materia, public_path(item) %>
<% end %>
<br />
I noticed that if I remove the public_path(item) the page works, so, is there any alternative to this?
THe only thing that sticks out to me is that you may have misspelled material in
<%= link_to item.materia, public_path(item) %>
this would throw an exception. You might want to check your logs as well

Resources