daveanderson88
daveanderson88

Reputation: 347

Using Slugs in ActiveAdmin Urls

I have set up my rails controller to use slugs instead of ids to identify a "Fitting" (for show/edit actions), so I can use a url like this to reach a show page:

http://localhost:3000/datasheets/slug-attribute-of-fiting

In routes.rb

resources :datasheets, only: [:index, :show, :edit], param: :slug

In datasheets_controller.rb

 def show
    fitting = Fitting.where(slug:(params[:slug])).first
    pdf = DatasheetPdf.new(fitting)
    send_data pdf.render, filename: "#{fitting.slug}-datasheet-#{Date.today}.pdf", type: 'application/pdf', disposition: 'inline'
  end

This is all working correctly, for the normal show view at the url mentioned above, but the problem occurs when adding the ActiveAdmin gem (which generates its own controllers that are not accessible as far as I am aware). If you try to edit a "Fitting" in the active admin dashboard, you are directed to http://localhost:3000/admin/fittings/slug-attribute-of-fiting/edit which returns the following error:

ActiveRecord::RecordNotFound in Admin::FittingsController#edit
Couldn't find Fitting with 'id'=slug-attribute-of-fiting

Given that I cannot get to the active admin controller (right?) how can I intercept the slug and use it to supply the id.

Thanks

Upvotes: 2

Views: 925

Answers (1)

daveanderson88
daveanderson88

Reputation: 347

Adding the following to app/admin/fittings.rb solved the issue:

controller do
    defaults :finder => :find_by_slug
end

Upvotes: 8

Related Questions