销毁错误不会显示在 Flash 消息中。
当模型定义为has_many
和restrict_with_error
:
class User
has_many :orders, dependent: :restrict_with_error
..
end
下面的代码可以修复它,但我真的认为这应该是默认行为:
after_destroy :check_model_errors
controller do
def check_model_errors(object)
return unless object.errors.any?
flash[:error] ||= []
flash[:error].concat(object.errors.full_messages)
end
end
错误处理/显示不是 AA 的一部分,它是 InheritedResources 的一部分
@kaspernj ,我发现这可以在 ActiveAdmin 中通过 I18n 翻译和在控制器中自定义响应者的插值选项来完成。
在初始化程序中将方法#interpolation_options
到ActiveAdmin::BaseController
中:
# config/initializers/active_admin.rb
class ActiveAdmin::BaseController
private
def interpolation_options
options = {}
options[:resource_errors] =
if resource && resource.errors.any?
"#{resource.errors.full_messages.to_sentence}."
else
""
end
options
end
end
然后覆盖语言环境文件中销毁警报消息的翻译:
# config/locales/en.yml
en:
flash:
actions:
destroy:
alert: "%{resource_name} could not be removed. %{resource_errors}"
@zorab47 的解决方案很棒,但是当我们尝试销毁嵌套对象(模型中的 acccept_nested_attributes 和 activeadmin 中的 f.has_many(:resources, allow_destroy: true) 时,请不要覆盖这些问题)。
作为_实验性猴子补丁_,我在 config/initializers/active_admin.rb 中添加以下内容:
ActiveAdmin::ResourceController::DataAccess.module_eval do
def update_resource(object, attributes)
if object.respond_to?(:assign_attributes)
object.assign_attributes(*attributes)
else
object.attributes = attributes[0]
end
begin
run_update_callbacks object do
save_resource(object)
end
rescue ActiveRecord::RecordNotDestroyed => e
flash[:error] = "Cannot destroy nested object."
object.errors.add(:base, e.to_s)
end
end
end
最有用的评论
@kaspernj ,我发现这可以在 ActiveAdmin 中通过 I18n 翻译和在控制器中自定义响应者的插值选项来完成。
在初始化程序中将方法
#interpolation_options
到ActiveAdmin::BaseController
中:然后覆盖语言环境文件中销毁警报消息的翻译: