【问题标题】:How to handle ActiveRecord::RecordNotUnique error如何处理 ActiveRecord::RecordNotUnique 错误
【发布时间】: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::RecordInvalidsave!
  • @Subash 并非所有英雄都在空中飞行,有时他们在键盘编码后面!谢谢冠军!你能把这个作为答案让我接受吗?
  • 顺便说一句,你怎么知道它的ActiveRecord::RecordInvalid
  • 很高兴为您提供帮助

标签: ruby-on-rails error-handling


【解决方案1】:

您可以使用ActiveRecord::RecordInvalid 而不是ActiveRecord::RecordNotUnique,因为这是save!create! 引发的异常。

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

【讨论】:

  • 谢谢我的家伙。你救了我。浪费了 2 小时。
猜你喜欢
  • 2015-02-06
  • 1970-01-01
  • 2015-09-08
  • 2014-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多