Ruby On Rails Classroom image

Pooja  Negi / Student / Web Technology

To post your Question Join Classroom
Lesson Topics's No:-  |1 | 2 | 3|Last
Lessons:-Validating Presence

  Validating Presence

Perhaps the most elementary validation is presence, which simply verifies that a given attribute is present. For example, in this section we’ll ensure that both the name and email fields are present before a user gets saved to the database. In Section 7.3.2, we’ll see how to propagate this requirement up to the signup form for creating new users.

              We’ll start with a test for the presence of a name attribute. Although the first step in TDD is to write a failing test (Section 3.2.1), in this case we don’t yet know enough about validations to write the proper test, so we’ll write the validation first, using the consoleto understand it. Then we’ll comment out the validation, write a failing test, and verify that uncommenting the validation gets the test to pass. This procedure may seem pedantic for such a simple test, but I have seen many ‘‘simple’’ tests that actually test the wrong thing; being meticulous about TDD is simply the only way to be confident that we’re testing the right thing. (This comment-out technique is also useful when rescuing an application whose application codeis already written but—quelle horreur!— has no tests.)

                 The way to validate the presence of the name attribute is to use the validates method with argument presence: true, as shown in Listing 6.9. The presence: true argument is a one-element options hash; recall from Section 4.3.4 that curly braces are optional when passing hashes as the final argument in a method. (As noted in Section 5.1.1, the use of options hashes is a recurring theme in Rails.)






Listing 6.9 may look like magic, but validates is just a method, as indeed is attr_accessible. An equivalent formulation of Listing 6.9 using parentheses is as follows:


Let’s drop into the console to see the effects of adding a validation to our User model:9


Here returns false, indicating a failed save. In the final command, we use the valid? method, which returns false when the object fails one or more validations, and true when all validations pass. In this case, we only have one validation, so we know which one failed, but it can still be helpful to check using the errors object generated on failure:


>> user. errors.full  messages
=> ["Name  can't  be   blank"]


(The error message is a hint that Rails validates the presence of an attribute using the blank? method, which we saw at the end of Section 4.4.3.) Now for the failing test. To ensure that our incipient test will fail, let’s comment out the validation at this point (Listing 6.10).

Pooja   Negi

Skills    Ruby On Rails

Qualifications :- High School - SSN high school, College/University - HNBGU, College/University - SRHU,
Location :-Ranipokhari,Rishikesh,Uttarakhand,India
Description:- Student

  Students (0)