ruby-on-rails - 当我在 Rails 中收到 PG::ForeignKeyViolation 错误时,如何显示一个闪现通知消息

标签 ruby-on-rails postgresql

我有 2 个模型,Bidding 和 BiddingItem。

class Bidding < ActiveRecord::Base
   has_many :bidding_items, dependent: :restrict_with_error
   accepts_nested_attributes_for :bidding_items, reject_if: :all_blank, allow_destroy: true
end

class BiddingItem < ActiveRecord::Base
   belongs_to :bidding
end

通过将以下依赖项添加到出价模型,我没有收到任何错误,但我仍然想向用户显示一条消息。

has_many :bidding_items, dependent: :restrict_with_error

我如何才能向用户显示一条快速通知消息而不是获取此错误 View 或完全没有错误(通过使用我之前提到的依赖项)?

enter image description here

最佳答案

您可以使用 ActiveSupport#rescue_from在您的 biddings_controller 中,并在 with 选项中传递一个已定义的私有(private)方法,以便在该 Controller 中每次发生此类错误时“引发”。

由于您可以在所使用的方法中定义任何逻辑,因此您可以重定向到相同的 biddings_path 并在 notice flash 中传递自定义消息,例如:

class BiddingsController < ApplicationController
  rescue_from ActiveRecord::InvalidForeignKey, with: :invalid_foreign_key

  private

  def invalid_foreign_key
    redirect_to biddings_path, notice: 'Some custom message.'
  end
end

您只需要确保在当前 View 中呈现通知

关于ruby-on-rails - 当我在 Rails 中收到 PG::ForeignKeyViolation 错误时,如何显示一个闪现通知消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46432434/

相关文章:

javascript - Rails Turbolinks 破坏 pnotify

ruby-on-rails - 功能在生产模式下不起作用

database - 为什么我不知道 PostGIS 是否正确安装在我的 PostgreSQL 数据库上?

postgresql - 记录 "new"尚未分配

ruby-on-rails - 将散列作为函数参数处理

ruby-on-rails - 仅当 Rails 中存在另一个变量时才设置变量

ruby-on-rails - capybara 和 Rspec。 capybara 不在测试中呈现页面,在 Rails 中使用访问或获取方法

sql - 如何从 .sql 脚本文件中获取 postgres 中自动递增列的值?

python - 如何在多个条件下更新值

postgresql - 无法从公共(public)子网中的虚拟机 ping 私有(private)子网中的 PostgreSQL