Rails模型数据验证 #
一、验证概述 #
1.1 什么是验证 #
验证确保数据在保存到数据库前符合特定规则,保证数据的完整性和一致性。
1.2 验证时机 #
createupdatesave
二、内置验证器 #
2.1 存在性验证 #
ruby
class Article < ApplicationRecord
validates :title, presence: true
validates :title, :body, presence: true
end
2.2 唯一性验证 #
ruby
class User < ApplicationRecord
validates :email, uniqueness: true
validates :email, uniqueness: { scope: :account_id }
end
2.3 长度验证 #
ruby
class Article < ApplicationRecord
validates :title, length: { minimum: 5 }
validates :title, length: { maximum: 100 }
validates :title, length: { in: 5..100 }
validates :title, length: { is: 50 }
end
2.4 格式验证 #
ruby
class User < ApplicationRecord
validates :email, format: { with: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i }
end
2.5 数值验证 #
ruby
class Product < ApplicationRecord
validates :price, numericality: { greater_than: 0 }
validates :quantity, numericality: { only_integer: true }
end
三、自定义验证 #
3.1 自定义验证方法 #
ruby
class Article < ApplicationRecord
validate :expiration_date_cannot_be_in_the_past
def expiration_date_cannot_be_in_the_past
if expiration_date.present? && expiration_date < Date.today
errors.add(:expiration_date, "can't be in the past")
end
end
end
四、条件验证 #
4.1 条件执行 #
ruby
class Order < ApplicationRecord
validates :card_number, presence: true, if: :paid_with_card?
def paid_with_card?
payment_type == 'card'
end
end
五、总结 #
5.1 核心要点 #
| 要点 | 说明 |
|---|---|
| presence | 存在性验证 |
| uniqueness | 唯一性验证 |
| length | 长度验证 |
| format | 格式验证 |
| 自定义验证 | 自定义验证方法 |
5.2 下一步 #
现在你已经掌握了数据验证,接下来让我们学习 查询接口,深入了解Rails的查询方法!
最后更新:2026-03-28