Rails Validation Helpers

Have you ever asked yourself, how can I make sure users signing up have a limited amount of characters for the username? How would we be able to achieve this? Well, Rails has a great way how to handle this with Active Record Validation Helpers.

According to documentation, these helpers provide common validation rules. Every time a validation fails, an error is added to the object’s errors collection, and this is associated with the attribute being validated.

Each helper accepts an arbitrary number of attribute names, so with a single line of code you can add the same kind of validation to several attributes.

So, we asked before how can I make sure users signing up have a limited amount of character for the username?

We can use our length validation helper within our User model and set either a minimum or a maximum to limit the length of characters the user can input. In this case, we will set a maximum of 8 characters. The user will need to have a username of only 8 characters. Let’s test this out:

class User < ApplicationRecordvalidations :username, length: { maximum: 8 }end

What if we want to add an error the the errors collection if the user has reached over the 8 characters? How can we implement this? According to documentation, we can add this to our validations:

class User < ApplicationRecordvalidations :username, length: { maximum: 8, too_long: "%{count} characters is the maximum allowed" }end

This will add “8 characters is the maximum allowed” as an error message if the user inputs more than 8 characters. For more information about this, click here, to view Ruby Documentation about Active Record Validations and Helpers.

Resources

Also, check out this video for visual assistance. If the video does not show, click here to view it.

I am a graduate from Flatiron School for Software Engineer. Studied HTML, CSS, Ruby, Ruby on Rails, JavaScript, React, Redux, Sinatra, and Sqlite3