我有一些问题。
在 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
或者也许我可以一次对所有页面更有用。
为此目的使用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
这里的另一个解决方案 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
我正在寻找一种方法来解决这个问题,而不需要自己手写按钮/操作链接。
在阅读了一些活动管理代码后,我发现了这个黑客:
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