### 测试代码:
class User < ApplicationRecord
...
validate :test1
...
private
def test1
logger.debug "=============== 测试 validate 是否被包含在事务中 ==============="
end
end
### rails consle 调试信息:
Running via Spring preloader in process 20000
Loading development environment (Rails 5.0.0.1)
irb(main):001:0> User.create
(0.1ms) begin transaction
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE "users"."email" IS NULL LIMIT ? [["LIMIT", 1]]
=============== 测试 validate 是否被包含在事务中 ===============
(0.1ms) rollback transaction
=> #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil, remember_digest: nil, admin: false, activation_digest: nil, activated: false, activated_at: nil, reset_digest: nil, reset_sent_at: nil>
irb(main):002:0>
回调
这个理应包含在事务中,但为什么要 验证
也要包含在事务中。在《rails tutorial》一书中,有如下一段代码:
class Micropost < ApplicationRecord
...
validate :picture_size
private
# 验证上传的图像大小
def picture_size
if picture.size > 5.megabytes
errors.add(:picture, "should be less than 5MB")
end
end
end
像这种 picture_size
验证,理应在事务外的。同样,实际项目中里的 model 也有许多 验证
没必要放在事务中的,那为什么 rails 却这么做了???