[Rails] ActiveAdmin - actions

Tags
Rails
Engineering
Created
Nov 1, 2023 03:26 AM
Edited
Oct 31, 2023
Description
ActiveAdmin - collection_action, member_action, action_item, …

collection_action

A collection action is a controller action which operates on the collection of resources.

method: :get

Triggered by GET request such as a button or a link.
Link could be something like:
# app/admin/my_models.rb

ActiveAdmin.register MyModel do
  # Define a custom action that operates on the collection of MyModel resources
  collection_action :filter, method: :get do
    # Display a form for filtering the resources
    render "admin/my_models/filter"
  end
end

# app/views/admin/my_models/index.html.arb

# Add a link to the custom action
div class: "actions" do
  span "Filter:"
  = link_to "Published", filter_admin_my_models_path(filter: "published")
  = link_to "Unpublished", filter_admin_my_models_path(filter: "unpublished")
end
In this way, clicking “Pubished” button will trigger filter collection_action.

member_action

A member action is a controller action which operates on a single resource.
ActiveAdmin.register User do

  member_action :lock, method: :put do
    resource.lock!
    redirect_to resource_path, notice: "Locked!"
  end

end

action_item

The first parameter is just a name/identifier of the action (required). action_item is a member action, which means that it operates on a single resource and is displayed in the actions menu of the resource.
action_item :name_of_action, only:show do
...
end

Add a button to a detailed page

There will be a button with text ("log in").
# app/admin/...rb
action_item :login, only: :show do
	link_to: 'log in', log_in_admin_...(params[:id])
end

member_action :log_in do
	# pass some params and do some logics
end
# app/view/admin/.../...arb
 

Add a button to parent page

There will be a button with text ("log in").
# app/admin/...rb
action_item :login, only: :index do
	link_to: 'log in', log_in_admin_...(params[:id])
end

collection_action :log_in. method: :get do
	# pass some params and do some logics
end
# app/view/admin/.../...arb

Source