Understanding Rails

Understanding Rails · Season 3: Active Record in depth

Validations and errors

Episode 21 · deep dive · about 6 minutes · Rails 8.1 · by

How was this episode?

The series' author reads every note, and no one else sees it. When something is wrong or unclear, it gets fixed and the episode re-cut. How this series stays right.

Was it clear?

Not endorsed yet. Are you a Rails developer? What's an endorsement?

Endorse this version To endorse: create an account, confirm your email, then link GitHub.

Built-in validators, custom ones, and showing errors in forms.

Free to watch. If it helped, support the series.

Transcript

0:00 Validations and errors

Episode twenty one. Validations and errors. A model decides what it's willing to save. Today: the validators Rails gives you, writing your own, and showing the errors in a form.

0:16 Rules in the model

Validations live in the model. Here's the note model, with one new line. Validates body, presence true, and a length of at most five hundred characters. Rails runs these rules before every save.

0:30 save returns false

Try to save a note with an empty body. Save returns false, and nothing reaches the database. The reasons wait on the note, in its errors. Full messages gives sentences, ready to show a person. Body can't be blank.

0:45 errors.details

You can ask for one attribute's messages, too. And details gives each error as a symbol: blank. Check the symbol in your code and your tests, because the wording can change, and the symbol doesn't.

0:59 save!

Save with a bang doesn't return false. It raises record invalid, with the messages inside. Use plain save when a person can fix the input, like a form. Use the bang when a failure would be a bug, like in a seed file or a job.

1:16 Messages and locales

Make the body five hundred and one characters long, and the length rule answers. Body is too long, maximum is five hundred characters. Rails writes these sentences for you, from its locale files, so you can reword them, or translate them.

1:32 Built-in validators

Rails ships a validator for most everyday rules. Presence. Length. Format, against a regular expression. Numericality. Inclusion in a list. Comparison, like an end date after a start date. And uniqueness.

1:48 belongs_to requires its record

And there's one you already have. Belongs to requires its record, by default. A note with no notebook says notebook must exist. Optional true turns that off, the way a note's parent is optional, because most notes aren't replies.

2:04 presence, uniqueness, format

Tags get three rules on one line. A name must be present, unique, and match a format: lowercase letters, numbers and dashes. The format has its own message. Try urgent again, and the name has already been taken. Try Big Ideas, and it can use only lowercase letters, numbers and dashes.

2:24 How uniqueness checks

Uniqueness works differently from the rest. To check it, Rails asks the database first. Select one from tags, where name is urgent. If nothing comes back, the save goes ahead. That's two steps, and two requests at the same moment can both pass the check, and both save.

2:43 A unique index

So back uniqueness with a unique index. A migration adds it, and now the database itself refuses the second one. Record not unique. Unique constraint failed. The validation gives people a friendly message. The index makes sure it stays true.

3:00 Methods that skip validations

Some methods skip validations completely. Update column wrote an empty body straight into the database, and the note is now invalid. Update all, insert all, and save with validate false skip them too. They're for when you know better than the rules, so use them on purpose.

3:18 A validate method

When no built-in validator fits, write a method. Validate, with no s, names a method that runs on every save. Here, a reply must stay in the same notebook as the note it replies to. If it doesn't, the method adds an error, and that error stops the save, like any other.

3:37 A validator class

When the same rule belongs on many models, make it a class. Its name ends in validator, it lives in app validators, and it has one method, validate each. Now no shouting true reads just like a built-in. An all capitals note gets body can't be all capitals, and its detail is shouting.

3:56 Old data, new rule

Here's the trap when you add a rule. Records saved before the rule existed may break it. Note nine is all capitals. Now any update to note nine fails, even one that doesn't change its body. In our app, two notes were already invalid. A validation guards new saves. It doesn't check what's already there.

4:17 on create

On create runs a rule only for new records. Old notes can be edited again, and new ones still can't shout. And when you can, fix the old data too.

4:28 Errors in the form

Now the form. The scaffold's form partial already shows errors. If the note has any, it counts them, and lists each full message.

4:37 Why 422

When the save fails, the controller renders the form again, with the status unprocessable content. Four twenty two. That status matters. Turbo submits the form, and a successful response must be a redirect. Answer a failed save with two hundred, and Turbo stops with an error: form responses must redirect to another location.

4:59 field_with_errors

Rails also wraps each field that has an error in a div, with the class field with errors. The label and the text area both get one, so one line of CSS can mark them red. If that extra div breaks your layout, field error proc in your config changes it.

5:17 The rules

So: put the rules in the model. Back uniqueness with an index. And when a save fails, render the form with four twenty two.

5:26 Next

Next: callbacks, and when they hide what your app does.

Check your understanding

  1. A note with an empty body fails its presence validation. What does note.save return, and what does note.save! do?

    • save returns false; save! raises ActiveRecord::RecordInvalid
    • Both return false
    • save raises; save! returns false
    • save returns nil; save! saves anyway
    Show answer

    save returns false; save! raises ActiveRecord::RecordInvalid. Plain save returns false and leaves the reasons in note.errors. The bang version raises with the messages inside. Source: Active Record Validations: validation triggers (Rails Guides 8.1).

  2. Tag validates uniqueness of name. Two requests save the tag urgent at the same moment. What can happen?

    • The second save always fails validation
    • Both can pass the check and both save, unless a unique index stops one
    • Rails locks the tags table during the check
    Show answer

    Both can pass the check and both save, unless a unique index stops one. The validation asks the database first, then saves. A unique index makes the database refuse the second one. Source: Active Record Validations: uniqueness (Rails Guides 8.1).

  3. Which call writes an empty body to the database, even though the note validates presence of body?

    • note.update(body: "")
    • note.save after setting body to ""
    • Note.create(body: "")
    • note.update_column(:body, "")
    Show answer

    note.update_column(:body, ""). update_column skips validations and writes straight to the database. Use it on purpose. Source: Active Record Validations: skipping validations (Rails Guides 8.1).

  4. A form posted with Turbo fails validation. The controller renders the form again with status 200. What happens?

    • Turbo shows the errors as normal
    • Turbo reloads the whole page
    • Turbo stops with an error, because a successful form response must be a redirect
    Show answer

    Turbo stops with an error, because a successful form response must be a redirect. Turbo expects a redirect after a form submission, unless the status is 4xx or 5xx. Render a failed save with 422. Source: Turbo Drive: redirecting after a form submission (Turbo Handbook).

Sources

Every example in this episode was run on Rails 8.1.4.1 and Ruby 4.0.2.

Comments

Sign in to comment or sign up.