respond_with @model失败 #destroy:将@model.errors[:base]附加到闪存?



我使用以下代码来销毁模型,以及响应者 gem 和FlashResponder

def destroy
@model.destroy
respond_with @model
end

如果模型销毁失败,则会显示一个flash[:alert]

警报:无法销毁模型。

通常,@model.errors[:base]中提供了有关为什么无法销毁模型的更多信息。有没有办法将其添加到闪存中?我很想同时显示原始消息和基本错误。

我尝试像这样设置闪光灯:

flash[:alert] = "#{@wcag_element.errors[:base].to_sentence}." if @wcag_element.errors[:base].any?
respond_with @model

但这不再显示原始消息。

目前最简单的解决方案似乎是简单地将闪光灯添加到[:notice]而不是[:alert],但这感觉并不对:

flash[:notice] = ...
respond_with @wcag_element

respond_with还支持一些选项,例如:alert:notice,如其 API 中所述:

https://github.com/plataformatec/responders/blob/02a18078aa9b6533c25fd28060f62f1452fd9157/lib/responders/flash_responder.rb#L64

respond_with(@user, :notice => "Hooray! Welcome!", :alert => "Woot! You failed.")

因此,您可以这样做respond_with @model, alert: 'Custom alert messsage'

我发现这是最简单的解决方案:

ApplicationController < ActionController::Base
private
def respond_with *args
options = args.extract_options!
resource = args.first
options[:alert] ||= resource.errors.full_messages.to_sentence if resource.errors.any?
super resource, options
end
end

这样,我就不必再在每个后代控制器中考虑它了。

最新更新