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.

First steps<br />

vides an environment for you to experiment with Ruby without having to create new<br />

files. The console prompt looks like this:<br />

Loading development environment (Rails 3.1.0.beta)<br />

irb(main):001:0><br />

At this prompt, 12 you can enter any valid Ruby and it’ll be evaluated. But for now, the<br />

purpose of opening this console is to test the newly appointed validation. To do this,<br />

try to create a new project record by calling the create method. The create method<br />

is similar to the new method, but it attempts to create an object and then a database<br />

record for it rather than just the object. You use it identically to the new method:<br />

irb(main):001:0> Project.create<br />

=> #<br />

Here you get a new Project object with the name attribute set to nil, as you should<br />

expect because you didn’t specify it. The id attribute is nil too, which indicates that<br />

this object is not persisted (saved) in the database.<br />

If you comment out or remove the validation from inside the Project class and<br />

type reload! in your console, the changes you just made to the model are reloaded.<br />

When the validation is removed, you have a slightly different outcome when you call<br />

Project.create:<br />

irb(main):001:0> Project.create<br />

=> #<br />

Here, the name field is still expectedly nil, but the other three attributes have values.<br />

Why? When you call create on the Project model, Rails builds a new Project object<br />

with any attributes you pass it 13 and checks to see if that object is valid. If it is, Rails sets<br />

the created_at and updated_at attributes to the current time and then saves it to the<br />

database. After it’s saved, the id is returned from the database and set on your object.<br />

This object is valid, according to Rails, because you removed the validation, and therefore<br />

Rails goes through the entire process of saving.<br />

The create method has a bigger, meaner brother called create! (pronounced create<br />

BANG!). Re-add or uncomment the validation from the model and type reload! in<br />

the console, and you’ll see what this mean variant does with this line:<br />

irb(main):001:0> Project.create!<br />

ActiveRecord::RecordInvalid: Validation failed: Name can't be blank<br />

12 Although you may see something similar to ruby-1.9.2-p180 :001 > too, which is fine.<br />

13 The first argument for this method is the attributes. If there is no argument passed, then all attributes default<br />

to their default values.<br />

79

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

Saved successfully!

Ooh no, something went wrong!