ruby-on-rails - ActiveRecord 异常未在服务对象中引发
问题描述
在构建服务对象RecordInvalid
时,应该不会抛出异常。相反,else
块中的代码每次都会运行。
# services/new_registration_service.rb
class NewRegistrationService
...
def perform
begin
account_create
rescue ActiveRecord::RecordInvalid => exception
OpenStruct.new(success?: false, user: user, account: account, error: exception.message)
else
# this is running every time
OpenStruct.new(success?: true, user: user, account: account, error: nil)
end
end
private
...
def account_create
# this is NOT saving, which I believe should
# throw the exception in the perform method
post_account_setup if account.save
end
...
end
这是我从规范中运行的,account: name
需要的地方:
post :create, params: { account: FactoryBot.attributes_for(:account, { name: nil }) }
即使当我puts
返回account.name
值时,它也是nil
......这应该是引发RecordInvalid
异常的原因。
# models/account.rb
class Account < ApplicationRecord
resourcify
has_many :users
validates :name, presence: true
end
有任何想法吗?
解决方案
def account_create
# Instead of this:
post_account_setup if account.save
# Do this:
account.save!
post_account_setup
end
调用save
而不是save!
不会引发异常;它会回来false
的。
或者,有些人会争辩说,像这样使用异常来控制流是不好的做法。因此,您可以执行以下操作:
def perform
# ...
if account.valid?
account.save! # This should never fail!
post_account_create
OpenStruct.new(success?: true, user: user, account: account, error: nil)
else
OpenStruct.new(success?: false, user: user, account: account, error: account.errors)
end
end
或者,类似地:
def perform
# ...
if account.save
post_account_create
OpenStruct.new(success?: true, user: user, account: account, error: nil)
else
OpenStruct.new(success?: false, user: user, account: account, error: account.errors)
end
end
推荐阅读
- java - Gradle 与 Ant Java Task 的等价物是什么?
- django-models - 将当前登录的用户分配给 Django 中的 ForeignKey 字段
- python - 脚本 a 需要来自脚本 b 的数据,但脚本 b 也需要来自脚本 a 的数据。可以双向导入吗?
- php - Laravel - 按“字段及其关系模型字段”之间的条件过滤模型
- image - FlexibleSpaceBar 背景图像在折叠时保持一定的不透明度
- mysql - LoadError:MySQL2 gem 问题,Ubuntu LTS 20.04 上的 libmysqlclient.so.20 版本不正确
- javascript - 如何将日期格式更改为“dd / mm / yy”?
- mongodb - 使用另一个日期字段的值更新 MongoDB 日期字段
- arrays - 在 Google 表格应用脚本中更新一批单元格时遇到问题
- html - 如何使用css更改标题属性的颜色?