在ActiveRecord中,当创建或更新记录时,可以使用验证器来验证模型的属性。如果验证失败,会抛出ActiveRecord::RecordInvalid异常。
下面是一个示例,展示了如何在验证失败时捕获异常,并处理验证失败的情况:
class Combination < ApplicationRecord
  belongs_to :technology
  # 添加验证器,确保技术组合必须存在
  validates :technology, presence: true
end
当你尝试创建或更新Combination记录时,如果关联的technology不存在,将会抛出ActiveRecord::RecordInvalid异常。
begin
  combination = Combination.new
  combination.save!
rescue ActiveRecord::RecordInvalid => e
  puts e.message # 输出异常信息
end
在上面的示例中,我们使用begin和rescue来捕获异常,并使用e.message输出异常信息。对于验证失败的情况,将输出类似于"Validation failed: Technology must exist"的异常消息。
你还可以根据具体的需求,自定义处理验证失败的逻辑,例如:
begin
  combination = Combination.new
  combination.save!
rescue ActiveRecord::RecordInvalid => e
  puts "验证失败:#{e.message}"
  # 处理验证失败的逻辑
end
通过捕获ActiveRecord::RecordInvalid异常,你可以在验证失败时采取相应的行动,例如显示错误消息、回滚事务或执行其他逻辑。