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 ~~~~! !!
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:
That's right. Validation to the model is only the judgment of Rails side (MVC), it is not reflected in mysql or DB.
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.
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.
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