Chris Kenworthy
Chris Kenworthy

Reputation: 129

Custom action_item with custom method in Active Admin

I have a nested resource in Active Admin which shows all SupportSessions (like meetings) for a particular SupportAllocation (which defines a teacher-pupil relationship):

ActiveAdmin.register SupportSession do
  belongs_to :support_allocation

On my index page, I'd like a button at the top that the user can click (like they can click 'New Support Session'), which then executes a custom method which sends an email using ApplicationMailer. There is no 'page' where the button goes to - it just redirects back to the current index page with a message indicating success or otherwise.

I can get the 'Request Approvals' button to appear on the index page with this code:

  # Adds a new button
  action_item only: :index  do
      link_to 'Request approvals', send_for_approval #custom method
  end

But obviously this raises an exception:

undefined local variable or method `send_for_approval'

Because I haven't defined this custom method anywhere.

I've created my mailer class but I'm not sure how to 'connect' it to my resource. I realise this will involve a new route of some sort, or use the existing 'put' method. I'd need to hand the current SupportAllocation ID to the method, so it knows which records/data to deal with when it sends email messages.

Any tips on how do I do create a button that runs this custom method + parameter? Where do I define this new custom method?

Thank you for your help.

Upvotes: 1

Views: 3284

Answers (1)

adesurirey
adesurirey

Reputation: 2620

You should code the action first, in your file:

member_action :send_for_approval, method: :patch do
  # send your email here you can access to :resource which is your record
  YourMailer.with(support_session_id: resource.id).your_email.deliver_now
  # redirect to your admin index or show path
end

Then rails routes will give you the correct path to it so you can pass it to action_item, it will look something like that:

action_item only: :index  do
   link_to 'Request approvals', send_for_approval_admin_support_session_path, method: :patch
end

References:

https://activeadmin.info/8-custom-actions.html#member-actions

https://activeadmin.info/8-custom-actions.html#action-items

Upvotes: 3

Related Questions