使用 bang (!)。
在需要很多东西(包括标题)的模型上,create 失败并触发您的回滚:
> Post.create(title: nil)
(0.1ms) BEGIN
Post Exists (0.2ms) SELECT 1 AS one FROM "posts" WHERE "posts"."slug" IS NULL LIMIT $1 [["LIMIT", 1]]
(0.1ms) ROLLBACK
=> #<Post:0x007fa44c934fc0
id: nil,
developer_id: nil,
body: nil,
created_at: nil,
updated_at: nil,
channel_id: nil,
title: nil,
slug: nil,
likes: 1,
tweeted: false,
published_at: nil,
max_likes: 1>
随着一声巨响,创建快速失败并引发RecordInvalid 错误:
> Post.create!(title: nil)
(0.1ms) BEGIN
Post Exists (0.2ms) SELECT 1 AS one FROM "posts" WHERE "posts"."slug" IS NULL LIMIT $1 [["LIMIT", 1]]
(0.1ms) ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Body can't be blank, Channel can't be blank, Developer can't be blank, Title can't be blank
from /Users/dev/.asdf/installs/ruby/2.3.3/lib/ruby/gems/2.3.0/gems/activerecord-5.0.1/lib/active_record/validations.rb:78:in `raise_validation_error'
要在 OP 上进行构建,可以使用 update_attributes 和 update_attributes! 来产生两种行为:
> Post.first.update_attributes(title: nil)
Post Load (0.2ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" ASC LIMIT $1 [["LIMIT", 1]]
(0.1ms) BEGIN
Developer Load (0.2ms) SELECT "developers".* FROM "developers" WHERE "developers"."id" = $1 LIMIT $2 [["id", 4], ["LIMIT", 1]]
Post Exists (0.2ms) SELECT 1 AS one FROM "posts" WHERE "posts"."slug" = $1 AND ("posts"."id" != $2) LIMIT $3 [["slug", "81e668bc4e"], ["id", 1], ["LIMIT", 1]]
(0.1ms) ROLLBACK
=> false
> Post.first.update_attributes!(title: nil)
Post Load (0.2ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" ASC LIMIT $1 [["LIMIT", 1]]
(0.1ms) BEGIN
Developer Load (0.2ms) SELECT "developers".* FROM "developers" WHERE "developers"."id" = $1 LIMIT $2 [["id", 4], ["LIMIT", 1]]
Post Exists (0.2ms) SELECT 1 AS one FROM "posts" WHERE "posts"."slug" = $1 AND ("posts"."id" != $2) LIMIT $3 [["slug", "81e668bc4e"], ["id", 1], ["LIMIT", 1]]
(0.1ms) ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Title can't be blank
from /Users/dev/.asdf/installs/ruby/2.3.3/lib/ruby/gems/2.3.0/gems/activerecord-5.0.1/lib/active_record/validations.rb:78:in `raise_validation_error'
什么是!?
! 在 Ruby 中通常意味着该方法将修改它所调用的对象。但是,ActiveRecord 有不同的约定; ! 方法“更严格,因为它们会引发异常。”
create docs
validation docs