Destroy errors are not shown in a flash message.
Happens when a model is defined with a has_many
with restrict_with_error
as such:
class User
has_many :orders, dependent: :restrict_with_error
..
end
The following code can fix it, but I really think this should be the default behavior:
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
The error handling / displaying is not part of AA, it is part of InheritedResources
@kaspernj, I found this can be accomplished within ActiveAdmin through I18n translations and customizing the Responders' Interpolation Options in the controller.
Adding the method #interpolation_options
to ActiveAdmin::BaseController
in an initializier:
# 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
Then overriding the translation for the destroy alert message in the locale file:
# config/locales/en.yml
en:
flash:
actions:
destroy:
alert: "%{resource_name} could not be removed. %{resource_errors}"
Solution by @zorab47 is great but don't cover the evenience when we are trying to destroy a nested object (accept_nested_attributes in the model and f.has_many(:resources, allow_destroy: true) in activeadmin).
As _experimental monkey patch_ I add the following in 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
Most helpful comment
@kaspernj, I found this can be accomplished within ActiveAdmin through I18n translations and customizing the Responders' Interpolation Options in the controller.
Adding the method
#interpolation_options
toActiveAdmin::BaseController
in an initializier:Then overriding the translation for the destroy alert message in the locale file: