First use the before_destroy model before_destroy to check if the record can be destroyed (here, if the student is signed):
class Student < ActiveRecord::Base before_destroy :before_destroy_check_for_groups def before_destroy_check_for_groups if StudentInGroup.exists?(student_id: self.id) errors.add(:base, I18n.t('app.student_signed_in')) return false end end end
It's simple and easy, and you do it for every model you want.
And here is the trick. You can apply a common patch to all Active Admin resources to pass the model error message to the user as a ResourceController callback. The following is the check_model_errors method. And this method should be registered as a callback during the execution of each call to the ActiveAdmin.register method (see Fixed run_registration_block ). You can simply paste the code below into a new file (of any name) in the config/initializers folder of your application (or any other folder that initializes when the application starts). I said this as config/initializers/active_admin_patches.rb .
class ActiveAdmin::ResourceController def check_model_errors(object) return unless object.errors.any? flash[:error] ||= [] flash[:error].concat(object.errors.full_messages) end end class ActiveAdmin::ResourceDSL alias_method :old_run_registration_block, :run_registration_block def run_registration_block(&block) old_run_registration_block(&block) instance_exec { after_destroy :check_model_errors } end end
Jakub
source share