Validations chạy trước save / create / update.
Nếu fail, record không được lưu và lỗi nằm trong record.errors.
ruby
class User < ApplicationRecord
validates :name, presence: true, length: { minimum: 2, maximum: 50 }
validates :email, presence: true,
format: { with: URI::MailTo::EMAIL_REGEXP },
uniqueness: { case_sensitive: false }
validates :age, numericality: { greater_than: 0 }, allow_nil: true
end
user = User.new(name: "", email: "bad")
user.valid? # => false
user.errors.full_messages # => ["Name can't be blank", "Email is invalid"]Dùng save! / create! để raise ActiveRecord::RecordInvalid thay vì trả false — tốt hơn trong business logic cần fail-fast.
Validations run before save / create / update.
On failure, the record is not persisted and errors live in record.errors.
ruby
class User < ApplicationRecord
validates :name, presence: true, length: { minimum: 2, maximum: 50 }
validates :email, presence: true,
format: { with: URI::MailTo::EMAIL_REGEXP },
uniqueness: { case_sensitive: false }
validates :age, numericality: { greater_than: 0 }, allow_nil: true
end
user = User.new(name: "", email: "bad")
user.valid? # => false
user.errors.full_messages # => ["Name can't be blank", "Email is invalid"]Use save! / create! to raise ActiveRecord::RecordInvalid instead of returning false — better in business logic where you want fail-fast behaviour.