27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

76 CHAPTER 3 Developing a real Rails application<br />

though, you should change the line in the feature that checks for the title on the page<br />

to the following:<br />

And I should see "TextMate 2 - Projects - Ticketee"<br />

When you run this feature, it should be broken:<br />

expected #has_content?("TextMate 2 - Projects - Ticketee")<br />

to return true, got false<br />

Now you can fix it by replacing the line that sets @title in your show template with<br />

this one:<br />

<br />

You don’t need Ticketee here any more because the method puts it in for you. Let’s<br />

replace the title tag line with this:<br />

<br />

<br />

<br />

<br />

Ticketee<br />

<br />

<br />

This code uses a new method called content_for?, which checks that the specified<br />

content block is defined. If it is, you use yield and pass it the name of the content<br />

block, which causes the content for that block to be rendered. If it isn’t, then you just<br />

output the word Ticketee, and that becomes the title.<br />

When you run this feature again, it passes:<br />

...<br />

And I should see "TextMate 2 - Projects - Ticketee"<br />

1 scenario (1 passed)<br />

7 steps (7 passed)<br />

That’s a lot neater now, isn’t it? Let’s create a commit for that functionality and push<br />

your changes:<br />

git add .<br />

git commit -m "Added title functionality for show page"<br />

git push<br />

Next up, we look at how to stop users from entering invalid data into your forms.<br />

3.2.5 Validations<br />

The next problem to solve is preventing users from leaving a required field blank. A<br />

project with no name isn’t useful to anybody. Thankfully, Active Record provides validations<br />

for this issue. Validations are run just before an object is saved to the database,<br />

and if the validations fail, then the object isn’t saved. When this happens, you want to<br />

tell the user what went wrong, so you write a feature that looks like the following listing.

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

Saved successfully!

Ooh no, something went wrong!