ActiveAdmin hide Delete action by condition

8k views Asked by At

I have some problem.

In ActiveAdmin I need hide DELETE action by condition.

I did it for #index page. But I don't know how do this trick with #show page.

Here's code:

index do
    selectable_column
    column :id do |package|
      link_to package.id, admin_subscription_package_path(package)
    end
    column :title
    column :plan_status
    column :duration do |package|
      if package.duration == 1
        "#{package.duration} day"
      else
        "#{package.duration} days"
      end
    end
    column 'Price (USD)', :price do |package|
      number_to_currency(package.price, locale: :en)
    end
    column :actions do |object|
      raw(
          %(
            #{link_to 'View', admin_subscription_package_path(object)}
            #{(link_to 'Delete', admin_subscription_package_path(object),
                       method: :delete) unless object.active_subscription? }
            #{link_to 'Edit', edit_admin_subscription_package_path(object)}
          )
      )

    end
  end

Or maybe I can do it more useful for all pages at once.

3

There are 3 answers

6
Andrey Deineko On BEST ANSWER

Use action_item for this purpose:

ActiveAdmin.register MyModel

  actions :index, :show, :new, :create, :edit, :update, :destroy

  action_item only: :show  do
    if condition
      link_to "Delete whatever", {action: :destroy}, method: :delete, confirm: 'Something will be deleted forever. Sure?'
    end
  end

end
0
Benjamin On

I was looking for a way to solve this without needing to hand-write the buttons / actions links myself.

After a bit of reading through the active admin code, I found this hack:


ActiveAdmin.register User do # replace User by the type of the resource in your list

  # ... your config, index column definitions, etc.

  controller do

    # ... maybe some other controller stuff

    def authorized?(action, resource) 
      return false unless super(action, resource)

      if resource.is_a? User # replace User by the type of the resource in your list
        return false if action == ActiveAdmin::Auth::DESTROY && condition  # replace condition with your check involving the resource
      end

      true
    end

  end
end
0
Alexandr On

Another solution from here https://groups.google.com/g/activeadmin/c/102jXVwtgcU

ActiveAdmin.register Foo do

  RESTRICTED_ACTIONS = ["edit", "update"]
  actions [:index, :show, :edit, :update]

  controller do
    def action_methods
      if current_admin_user.role?(AdminUser::ADMIN_ROLE)
        super
      else
        super - RESTRICTED_ACTIONS
      end
    end
  end

  ...
end