[RUBY] Hey hey validation should be written in either the model or the migration file yo

This is the second article today. I want to drink beer, but I haven't. !! (Because I write an article while drinking and I am desperate if there are many typographical errors): frowning2:

Well, this time about the place to write validation. : cop:

I'll be enthusiastic ~~~~! !!

1 Validation to model

user.rb


  validates :email,           presence: true
  validates :first_name,      presence: true
  validates :last_name,       presence: true, length: { maximum: 15 }

I think I write it like this. To explain

[Email] Cannot save value in the sky [First_name] Empty and cannot save value [Last_name] The value cannot be saved as empty, and it cannot be saved unless it is within 15 characters.

I will write a validation like that. Then there is no problem with this! !! I think show. : santa:

With this, validation will not be required when typing directly into mysql (DB)! !!

That's right. Validation to the model is only the judgment of Rails side (MVC), it is not reflected in mysql or DB.

2 Then validate the migration file!

migrate/create_users.rb


      t.string :first_name,         null:false
      t.string :last_name,          null:false
      t.string :email,              null:false

Here, the column is validated so that it cannot be saved with an empty value.

Then you only need to validate the migration file, right?

You might think that. However, when I ask the DB to perform a validation check, an error that is difficult to understand is returned, or Or, if you write the validation properly in the model, you can get an error message, which is versatile.

3 Results It is better to write in both

The result is this. It may be annoying, but it's safe to write on both. : family_wwb:

There are such merits! There is such a danger! If you have any supplementary information, I would appreciate it if you could let me know.

Thank you for reading! : ok_hand_tone1:

Recommended Posts

Hey hey validation should be written in either the model or the migration file yo
Solution if you delete the migration file in the up state
[Rails] Where to be careful in the description of validation
[Swift5] How to create a .gitignore file and the code that should be written by default