如何处理ActiveRecord :: RecordNotUnique错误

时间:2019-05-01 23:18:18

标签: ruby-on-rails error-handling

我是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]并简短地重定向,它只会执行{{ 1}},即使它出错了。同样,在begin上,当我添加@department.save时(如果输入的名称不是唯一的话),我会收到我想要的错误!,但它不会重定向,而是转到错误画面。

这里不见了吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用ActiveRecord::RecordInvalid代替ActiveRecord::RecordNotUnique,因为那是save!create!引发的异常。

我想我遇到了,不记得是什么时候,看看here