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.

94 CHAPTER 4 Oh CRUD!<br />

Figure 4.1 ActiveRecord::RecordNotFound exception<br />

The ActiveRecord::RecordNotFound exception is Rails’ way of displaying exceptions<br />

in development mode. Underneath this error, more information is displayed, such as<br />

the backtrace of the error.<br />

If you were running in the production environment, you would see a different error.<br />

Stop the server that is currently running, and run these commands to start in production<br />

mode:<br />

rake db:migrate RAILS_ENV=production<br />

rails server -e production<br />

Here you must specify the RAILS_ENV environment variable to tell Rails you want to<br />

migrate your production database. By default in Rails, the development and production<br />

databases are kept separate so you don’t make the mistake of working with production<br />

data and deleting something you shouldn’t. This problem is also solved by<br />

placing the production version of the code on a different server from the one you’re<br />

developing on. You only have to run the migration command when migrations need<br />

to be run, not every time you need to start your server.<br />

You also pass the -e production option to the rails server command, which<br />

tells it to use the production environment. Next, navigate to http://[our-localip]:3000/project/not-here,<br />

where [our-local-ip] is whatever the IP of your computer is<br />

on the local network, like 10.0.0.2 or 192.168.0.3. When you do this, you get the standard<br />

Rails 404 page (see figure 4.2), which, to your users, is unhelpful.<br />

It’s not the page that’s gone missing, but rather the resource you’re looking for isn’t<br />

found. If users see this error, they’ll probably have to click the Back button and then<br />

refresh the page. You could give users a much better experience by dealing with the<br />

error message yourself and redirecting them back to the home page.<br />

To do so, you capture the exception and, rather than letting Rails render a 404<br />

page, you redirect the user to the index action with an error message. To test that<br />

users are shown an error message rather than a “Page does not exist” error, you’ll<br />

write an RSpec controller test rather than a Cucumber feature, because viewing projects<br />

that aren’t there is something a users can do, but not something they should do.<br />

Plus, it’s easier.<br />

Figure 4.2 “Page does not exist” error

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

Saved successfully!

Ooh no, something went wrong!