Rails quick tips – How to restrict deleting action and showing flash notice in ActiveAdmin if data have child record

In 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_error

In ActiveAdmin you can use restrict_with_error to restrict deleting action from admin.

class Book < ApplicationRecord
  has_many :orders, dependent: :restrict_with_error
end

But it would not showing the message why we can’t delete the data.

restrict_with_exception

What 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.rb

class Book < ApplicationRecord
  has_many :orders, dependent: :restrict_with_exception
end

In file app/admin/books.rb

ActiveAdmin.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
end

Then it will show the error message at flash notice

Here is our Ruby on Rails quite tips, see you next time!

The post Rails quick tips – How to restrict deleting action and showing flash notice in ActiveAdmin if data have child record appeared first on CoinGecko Blog.

You May Also Like