When we deal with data input from users, we want to handle valid information for our database to process. If not, we start to deal with invalid values that invites chaos all around.
If anything, we would have to write a bunch of defensive conditionals, if/else/elsif/end statements, to deal with any invalid information. This can get tiresome and who has time for that?
By using the "validations" feature of ActiveRecord, we can create validation rules that will disregard any user input if the conditions are not met.
Here is an example of one: /app/models/[Class_name].rb
class User < ApplicationRecord
validates(:username, {
:presence => true,
:uniqueness => { :case_sensitive => false },
})
end
What is happening in the example above?
-
Inside of the Class "User" we use the method validates which takes in two arguments.
First argument: a Symbol that represents the name of the column we are declaring constraints for (i.e. "username").
Second argument: a Hash that defines the constraints we are applying (i.e. Common ones to use: :presence, :uniqueness, and :numericality).
-
What do these do?
- :presence -> an input NEEDS to be present.
- :uniqueness -> values can NOT be a duplicate.
- :numericality -> validates that the value input only has numeric values.
Essentially, the example above is saying:
-> When creating a new User class, the user input MUST have a "username" info present AND it has to be a unique value within the User database.
One more practice!
What does this say?
class FollowRequest < ApplicationRecord
validates(:sender, { :presence => true})
validates(:recipient, { :presence => true })
validates(:recipient_id, {
:uniqueness => { :scope => [:sender_id] }
})
end
Answer:
The column "sender" should have a value present during user input.
The column "recipient" should have a value present during user input.
The column "recipient_id" should have a unique value from the "sender_id" column.
WOHOOOO! Check your data! It'll help in the long run.
CY@.
Top comments (0)