代码清单 6.9:为 name 属性添加存在性验证 GREEN
app/models/user.rb
class User < ApplicationRecord
validates :name, presence: true
end
代码清单 6.9 中的代码看起来可能有点儿神奇,其实 validates 就是个方法。加入括号后,可以写成:
class User < ApplicationRecord
validates(:name, presence: true)
end
打开控制台,看一下在 User 模型中加入验证后有什么效果: 10
$ rails console --sandbox
user = User.new(name: “”, email: “mhartl@example.com”)
user.valid?
=> false
这里我们使用 valid? 方法检查 user 变量的有效性,如果有一个或多个验证失败,返回值为 false ;如果所有
验证都能通过,返回 true 。现在只有一个验证,所以我们知道是哪一个失败,不过看一下失败时生成的 er-
rors 对象还是很有用的:user.errors.full_messages
=> [“Name can’t be blank”]
(错误消息暗示,Rails 使用 4.4.3 节介绍的 blank? 方法验证存在性。)
因为用户无效,如果尝试把它保存到数据库中,操作会失败:user.save
=> false
加入验证后,代码清单 6.7 中的测试应该可以通过了:
但是我的是:
rails console --sandbox
Loading development environment in sandbox (Rails 6.0.2.2)
Any modifications you make will be rolled back on exit
irb(main):001:0> user = User.new(name: "", email: "mhartl@example.com")
(0.1ms) begin transaction
=> #<User id: nil, name: "", email: "mhartl@example.com", created_at: nil, updated_at: nil>
irb(main):002:0> user.valid?
=> true
irb(main):003:0> user.errors.full_messages
=> []
irb(main):004:0> user = User.new(name: "", email: "mhartl@example.com")
=> #<User id: nil, name: "", email: "mhartl@example.com", created_at: nil, updated_at: nil>
irb(main):005:0> user.valid?
=> true
irb(main):006:0> user.save
(0.1ms) SAVEPOINT active_record_1
User Create (5.1ms) INSERT INTO "users" ("name", "email", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["name", ""], ["email", "mhartl@example.com"], ["created_at", "2020-04-17 08:11:42.738300"], ["updated_at", "2020-04-17 08:11:42.738300"]]
(0.1ms) RELEASE SAVEPOINT active_record_1
=> true
问题出在哪里了?
问题解决了,把另一个测试成功的代码黏贴过来,成功了。应该是代码打错了。
irb(main):004:0> user = User.new(name: "", email: "mhartl@example.com")
(0.1ms) begin transaction
=> #<User id: nil, name: "", email: "mhartl@example.com", created_at: nil, updated_at: nil>
irb(main):005:0> user.valid?
=> false