我有 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 或完全没有错误(通过使用我之前提到的依赖项)?
最佳答案
您可以使用 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/