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 %>
Related
Rails each do method is acting strangely and I do not know why.
controller
def index
#fabric_guides = FabricGuide.with_attached_image.all.order(:name)
end
index.html.erb
<div class="guide-items">
<%= #fabric_guides.each do |fabric| %>
<div class="guide-container">
<%= link_to fabric_guide_path(slug: fabric.slug) do %>
<%= image_tag fabric.image if fabric.image.attached? %>
<% end %>
<div class="guide-info">
<p class="g-name">
<%= link_to fabric.name,
fabric_guide_path(slug: fabric.slug) %>
</p>
</div>
</div>
<% end %>
</div>
I have two FabricGuide records so I expect two "guide-container" but I get three. Or more precisely I get two guide containers and a third block of text containing all the content from the last FabricGuide record.
I have almost an identical setup for articles and have never encountered this problem. I'd happily share more information if needed. Thank you!
Please remove = equal sign from your each loop of view code
like below :-
<% #fabric_guides.each do |fabric| %>
...
...
<% end %>
you have used this <%= #fabric_guides.each do |fabric| %> in your view that's why it shows all record in DOM.
The expression for erb tags is <% %>
now if we want to print that tag too then we apply <%= %>
Looking for ways to improve the particularly bad performance I'm getting from my rails application. Here's the code from the page in question:
notifications_controller.rb
class NotificationsController < ApplicationController
def index
#questions = Question.all.order(:updated_at => :desc)
#users = User.all
#answers = Answer.all.order(:updated_at => :desc)
end
end
and here's the corresponding view. I know it's ugly but it's working.
<div>
<% if current_user %>
<div class="notifications-added col-md-8">
<h4 class="col-md-offset-2">Approvals & Answers</h4>
<span class="text-center">
<% current_user.questions.order(id: :desc).each do |question| %>
<% if question.approved == true %>
Your question, <%= link_to "#{question.title}", question_path(question) %>, has been <span class="notifications">approved.</span><br>
<% end %>
<% question.answers.each do |answer| %>
<%= answer.user.name %> <span class="notifications">added an answer</span> to your question, <%= link_to "#{question.title}", question_path(question) %>.<br>
<% end %>
<% end %>
</span>
</div>
<div class="notifications-voted col-md-4">
<h4 class="text-center">Votes</h4><span></span>
<% current_user.answers.order(updated_at: :desc).each do |answer| %>
<% #users.each do |user| %>
<% if user.voted_up_on? answer %>
<%= user.name %> <span class="notifications">upvoted</span> your answer to <%= link_to "#{Question.find(answer.question_id).title}", question_path(answer.question_id) %>.<br>
<% elsif user.voted_down_on? answer %>
<%= user.name %> <span class="notifications">downvoted</span> your answer to <%= link_to "#{Question.find(answer.question_id).title}", question_path(answer.question_id) %>. <br>
<% end %>
<% end %>
<% end %>
</div>
<% end %>
</div>
I think I'm just sorting too much. The page is taking a long time to load. What's the low hanging fruit for improving my performance? Any thoughts? Thanks in advance.
The first , you should move logic code in your view into model.
The second , use pluck method instead array active record objects. Array string are lightweight than array of active record. Right ?
The third , use slim template engine instead erb template engine.
The fourth , cache db.
The fiveth, use google PageSpeed plugin for google chrome to analytic what's slow.
Peter answer is correct, and I will add two things :
Eager loading
Doing this
current_user.questions.each do |question|
question.answers.each do |answer|
...
end
end
will generate a query for each question. Rails will load all the questions, then for each question load its associated answers (1 query + 1 query for any question).
If you replace the first line by
current_user.questions.include(:answer).each do |question|
Rails will load all the questions, then all the associated answers (2 queries).
Look at the log
Every information for any bad performance should be visible on logs in development mode. For example, if voted_up need to load any other models than answer, your query number will be too big.
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!".
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.
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.