用户模型验证:从存在性到唯一性的全面指南
1. 存在性验证
存在性验证是最基础的验证方式,它用于确保给定的属性不为空。在用户模型中,我们需要确保用户的姓名和电子邮件字段在保存到数据库之前都存在。
1.1 姓名存在性验证测试
以下是一个测试姓名属性存在性的示例代码:
# test/models/user_test.rb
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: "Example User", email: "user@example.com")
end
test "should be valid" do
assert @user.valid?
end
test "name should be present" do
@user.name = " "
assert_not @user.valid?
end
end
在这个测试中,我们将 @user 的姓名属性设置为一个空字符串,然后使用 assert_not 方法检查生成的 User 对象是否无效。
1.2 实现姓名存在性验证
为了使上述测试通过,我们需要在 User 模型中添加存在性验证:
超级会员免费看
订阅专栏 解锁全文
1056

被折叠的 条评论
为什么被折叠?



