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.

Developing your first application<br />

should note here that this doesn’t call the new action/method again 14 but only renders<br />

the template.<br />

You can make the creation of the @purchase object fail by adding a validation.<br />

Let’s do that now.<br />

1.2.7 Validations<br />

You can add validations to your model to ensure that the data conforms to certain<br />

rules or that data for a certain field must be present or that a number you enter must<br />

be above a certain other number. You’re going to write your first code for this application<br />

and implement both of these things now.<br />

Open up your Purchase model and change the whole file to what’s shown in the<br />

following listing.<br />

Listing 1.7 app/models/purchase.rb<br />

class Purchase < ActiveRecord::Base<br />

validates_presence_of :name<br />

validates_numericality_of :cost, :greater_than => 0<br />

end<br />

You use the validates_presence_of method to define a validation that does what it<br />

says on the box: validates that the field has a value. The other validation method,<br />

validates_numericality_of, does more than what it initially claims: it validates that<br />

the cost attribute is a number and that it is greater than 0.<br />

Let’s test out these validations by going back to http://localhost:3000/purchases,<br />

clicking New Purchase, and clicking Create Purchase. You should see the errors shown<br />

in figure 1.5.<br />

Figure 1.5<br />

Errors on purchase<br />

14 To do that, you call redirect_to new_purchase_path, but that wouldn’t persist the state of the<br />

@purchase object to this new request without some seriously bad hackery. By rerendering the template, you<br />

can display information about the object if the object is invalid.<br />

13

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

Saved successfully!

Ooh no, something went wrong!