27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Page and action caching<br />

However, when you click the Ticketee Beta link to go to your first project, the page<br />

will change to saying that you’re signed in as the admin@ticketee.com user again, as<br />

shown in figure 16.8.<br />

You know better; you’re actually signed in as the user! This is happening because<br />

Rails has cached the entire page, rather than just the tickets list. This page also<br />

ignores any kind of authorization you’ve set up in your controllers, making it available<br />

for every single person who wishes to access it, which is just a Very Bad Thing.<br />

So it looks like caches_page isn’t going to work in this situation. This method is<br />

better for pages that don’t have dynamic elements on them, such as the place at the<br />

top that displays the currently logged-in user or the list of tickets.<br />

This method has a brother called caches_action that will help you fix both the<br />

issue of the currently logged-in user display message, as well as the issue of it only<br />

showing the first page of pagination.<br />

16.3.2 Caching an action<br />

Caching an entire page is helpful when you don’t have authentication, but if you have<br />

authentication then it’s better to cache the response of the action on a per-user basis.<br />

Caching an action involves caching the response for a particular session, so that when<br />

that user requests it again they’ll be shown it again.<br />

Caching a page is great for a page that’s accessible by anybody, as the body would<br />

be served as a static file from the public folder by the web server. Caching an action is<br />

best used for actions that take a long time to process (you don’t have any at the<br />

moment) and that require some interaction with the Rails stack, such as a<br />

before_filter that authenticates your user.<br />

There’s a third way of caching, and that’s fragment caching, where you’d cache just a<br />

bit of a page at a time, rather than the entire result. Before you get on to using that,<br />

let’s see what caches_action provides you.<br />

NOTE Before you do anything, you’ll want to remove the old file that has<br />

been cached. To do this, delete the public/projects directory. Next time<br />

this page is requested, the cache will be re-created.<br />

Let’s replace this line in your ProjectsController<br />

caches_page :show<br />

Figure 16.8 Still signed in<br />

as admin@ticketee.com?<br />

451

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!