【发布时间】:2019-09-20 11:15:04
【问题描述】:
我是 Ruby on Rails 的新手,我一直在寻找如何处理 Ruby 上的错误并找到了这个链接,但它们都不起作用。
redirect_to is not working into rescue block
https://www.ruby-forum.com/t/begin-rescue-not-working/118832/5
Rails 3: Handle ActiveRecord::RecordNotUnique Exception
https://www.honeybadger.io/blog/ruby-exception-vs-standarderror-whats-the-difference/
在我的创建方法中我有这个
def create
@departments = Spree::Department.new(department_params)
begin
@departments.save
flash[:success] = 'Department Created'
redirect_to admin_departments_path
rescue ActiveRecord::RecordNotUnique => e
flash[:notice] = 'Department name already exists'
redirect_to admin_departments_path
return
end
end
但问题是它不会转到rescue 块,因此它不会呈现flash[:notice],它将呈现flash[:success],简而言之,它只会执行begin,即使它出错了.
同样在@department.save 上,当我添加!(砰)时,如果我输入一个不唯一的名称,我会收到一个错误Validation failed: Name has already been taken,这是我想要的,但它不会重定向,而是会出错屏幕。
这里有什么遗漏吗?
【问题讨论】:
-
尝试将
ActiveRecord::RecordNotUnique更改为ActiveRecord::RecordInvalid和save! -
@Subash 并非所有英雄都在空中飞行,有时他们在键盘编码后面!谢谢冠军!你能把这个作为答案让我接受吗?
-
顺便说一句,你怎么知道它的
ActiveRecord::RecordInvalid? -
很高兴为您提供帮助
标签: ruby-on-rails error-handling