Performance: Why validations protect data integrity
Validations affect server response time and database consistency by preventing invalid data from being saved.
class User < ApplicationRecord validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP } validates :age, numericality: { greater_than_or_equal_to: 0 } end User.create(email: "", age: -5) # fails validation, no save
class User < ApplicationRecord # No validations end # Controller saves without checks User.create(email: "", age: -5)
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No validations | 0 | 0 | 0 | [X] Bad |
| Model validations before save | 0 | 0 | 0 | [OK] Good |
email?validates with attribute and options.validates :email, presence: true is the modern and correct form.validates + attribute + option [OK]class User < ApplicationRecord
validates :age, numericality: { greater_than_or_equal_to: 18 }
endage = 16?class Product < ApplicationRecord validates :name, presence: true validates :price, numericality: true end
Product.new(name: '', price: 'free') fail?User model's username is unique and not empty. Which validation setup correctly protects data integrity?validates with multiple options in one line for clarity.presence: true and uniqueness: true correctly together.Pass the test and this pattern moves unknown