Validations are necessary to prevent invalid data from being persisted into the database. They are necessary to allow for efficient data entry and processing, and prevent uncessary situations such as empty user-name fields pushing empty strings into a database.
ActiveRecord has a number of simple declarative validations, such as
validates_confirmation_of. The one validation that I think would come in quite handy is the
validates_format_of validation. According to the “Rails 4 Way”, it’s heavily dependent upon regular expressions, but it’s an invaluable way to check the formats of email addresses, web URIs, etc.
You can also place constraints upon your validations. For example, if you’re using
validates_length_of for usernames, you can specify a range that the length must fall between. For example:
1 2 3
If it exceeds the length, then you can provide an error message option that follows the validation.
1 2 3
An important aspect of validations is enforcing uniqueness among join models in the database. We have used this recently (in our Flatiron-Kitchen-Ruby-003 assignment). In order to enforce uniqueness, we have to define a scope constraint. For example, if we had three classes,
Student, how could we make sure that a student isn’t registered more than once for a particular class? We would define the scope of the
Registration class, as shown below:
1 2 3 4 5
Another one that you run into all the time:
1 2 3
In short, validations help you place constraints upon your code to make it less error-prone in regards to data persistence. Think of validations as a gatekeeper for your application data – it lets the good pieces in, and keeps the bad ones out, assuming that you have the proper constraints in place.