ActiveAdmin 隐藏按条件删除操作

问题描述 投票:0回答:3

我有一些问题。

在 ActiveAdmin 中,我需要按条件隐藏 DELETE 操作。

我是为

#index
页面做的。但我不知道如何用#show page 来实现这个技巧。

代码如下:

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

或者也许我可以一次对所有页面更有用。

ruby-on-rails ruby-on-rails-4 ruby-on-rails-5 activeadmin ruby-on-rails-6
3个回答
8
投票

为此目的使用action_item:

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

2
投票

这里的另一个解决方案 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

1
投票

我正在寻找一种方法来解决这个问题,而不需要自己手写按钮/操作链接。

在阅读了一些活动管理代码后,我发现了这个黑客:


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
© www.soinside.com 2019 - 2024. All rights reserved.