How to restrict deleting action and showing flash notice in ActiveAdmin if data have child record
ReadIn this post, we are going to share a quick tips about how to restrict deleting action and showing customised flash notice in ActiveAdmin. We use this data model to demonstrate how we do it.A book has many orders, and we want to restrict deleting action of the book and showing error message in Active Admin if book is accociated to the orders. We have two ways to restrict the delete action, which are using dependent: :restrict_with_error and dependent: :restrict_with_error in your model file.restrict_with_errorIn ActiveAdmin you can use restrict_with_error to restrict deleting action from admin.class Book < ApplicationRecord has_many :orders, dependent: :restrict_with_error endBut it would not showing the message why we can’t delete the data.restrict_with_exceptionWhat if we want to show the error message in flash notice, we can use restrict_with_exception to raise an exception and overriding the destroy action in ActiveAdmin to show the message. Here is how we do.In file app/models/book.rbclass Book < ApplicationRecord has_many :orders, dependent: :restrict_with_exception endIn file app/admin/books.rbActiveAdmin.register Book do permit_params :title, :author controller do def destroy begin resource.destroy redirect_to admin_books_path, notice: "Book successfully deleted!" rescue ActiveRecord::DeleteRestrictionError => e redirect_to resource_path(resource), notice: e.message # can use e.message to get error from Rails or customise your message end end end endThen it will show the error message at flash noticeHere is our Ruby on Rails quite tips, see you next time!

