top of page
Search
  • Writer's pictureKayla Miller

Validations

When using a database, there needs to be checks that the data being added, removed, or altered is copacetic, and never a threat to the security or functionality of the database. Active Record includes validation features so data offered to the database can be validated before being accepted and persisted.


For the following example, let’s imagine you have a Rails application or Rails API set up, scaffolded, the whole shebang. You have a user class with the following attributes: username, password, bio. There’s also a posts class, and a user can have many posts. Your user class may look like this:

class User < ApplicationRecord has_many :posts, dependent: :destroy end

So there’s a class User which inherits from ApplicationRecord and has a has_many relationship to :posts. Notice that dependent: :destroy is assigned to the has_many relationship, signifying that all posts belonging to a user should be deleted if that user is deleted. Also, note that no attr_accessor, is specified for the user attributes since they are mapped to the database table. Imagine a real world scenario being a form submission from the client side. What would happen if the user didn’t include a bio, or submitted a password that was one character in length? There’s a need to control the data our application is using, for organization, or, at the most extreme, protection from hackers. The client side of an application can validate form data, but there needs to be an insurance on the server side, which, ideally, is inaccessible. This is where Active Record validations come in. Validations can be used in different ways, but a great place to start is with the even more helpful validation helpers that Active Record provides. These helpers are established to provide common use validations like whether a required field was entered or an entry matches the required length of characters. Let’s add some validations for our user attributes. We’ll start with the presence validation, which checks that the required field is not blank.

class User < ApplicationRecord has_many :posts, dependent: :destroy

validates :username, :password, :bio, presence: true

end

How easy is that?! The key word validates precedes the attributes to be validated (separated by commas), and is succeeded by the presence validator, assigned the condition true. The presence validator checks that the attribute is not nil or an empty string.


14 views0 comments

Recent Posts

See All

Job Search

I started my job search earlier this month and it is more challenging to find a good fitting job. I had a couple job offers however a lot...

Comments


Post: Blog2_Post
bottom of page