Search code examples
ruby-on-railsactiveadmin

Can I override to_param in model from activeadmin form submit


I have inherited a system that was created using Active Admin. I needed to add one of the models, "report", into Active Admin. I did this, checked the index displays in the dashboard and all looked well. However, when I tried to use any of the CRUD functionality it breaks returning the error:

Couldn't find Report with id=name_of_report

The problem is Active Admin is producing routes like this (where report_title is the report.title value):

http://localhost:3000/admin/reports/report_title

instead of:

http://localhost:3000/admin/reports/1

A look at the model shows that the problem is related to the report model having a to_param method:

def to_param
  title
end

If I remove this then my active admin pages start to work fine. However, a large amount of report functionality has been written which breaks if I remove the to_param because it needs the URL to be in format detailed above (http://localhost:3000/admin/reports/).

I've managed to create my own links using "link_to" for add, view, delete (see below). I also have the new link working in a similar way.

app/admin/reports.rb

index do
  selectable_column
  column :title
  column :id
  column :column_method
  column :row_method

  actions defaults: false do |action|
    link_to("View",   admin_report_path(action.id),      { :class=> "member_link view_link" } ) + 
    link_to("Edit",   edit_admin_report_path(action.id), { :class=> "member_link view_link" } ) + 
    link_to("Delete", admin_report_path(action.id),      { :class=> "member_link view_link" },  method: :delete, data: { confirm: 'Are you sure?' })
  end
end

The problem is I can't get the form to update or create the details from the form when it's submitted.

I was wondering if anyone else has experienced this problem and knew of way of getting around it?

Many thanks in advance for any suggestions.

EDIT

Timo's solution worked fine for me, many thanks for such a speedy response. For those interested my report.rb program now looks like this:

ActiveAdmin.register Report do

  controller do
    resources_configuration[:self][:finder] = :find_by_title
  end

  index do
    selectable_column
    column :title
    column :id
    column :column_method
    column :row_method

    actions

  end

  form do |f|
    f.inputs 'Details' do
      f.input :title
      f.input :column_method
      f.input :row_method
      f.input :id     # This should probably be hidden.....

      f.buttons
    end
  end

end

Solution

  • ActiveAdmin.register Report do
      controller do
        resources_configuration[:self][:finder] = :find_by_title
      end
    end
    

    Source: #method_for_find method in activeadmin/inherited_resources.