Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveAdmin with friendly id

I am using friendly_id in my rails 4 application with slug. Now I am using active_admin gem.

Problem:

When I click on show link from active admin for Group resource, It is throwing the following exception:

ActiveRecord::RecordNotFound at /admin/groups/username20-s-group-1

I guess, I need to override some of the active_admin default functions?

like image 951
przbadu Avatar asked Nov 20 '14 06:11

przbadu


3 Answers

There are cases, when application has quit a few resources, hence in order to keep it DRY there is a nice solution requiring few lines of code for whole application - simply override activeadmin's resource controller.

Create config/initializers/active_admin_monkey_patching.rb file with the following content:

ActiveAdmin::ResourceController.class_eval do
  def find_resource
    finder = resource_class.is_a?(FriendlyId) ? :slug : :id
    scoped_collection.find_by(finder => params[:id])
  end
end

Do not forget to restart the server.

like image 141
Andrey Deineko Avatar answered Nov 04 '22 06:11

Andrey Deineko


A better approach to @AndreyDeineko's is to override ActiveAdmin::ResourceController's find_resource method in config/initialisers/active_admin.rb and leverage the methods provided by FriendlyId (5.x at this point):

In config/initialisers/active_admin.rb:

ActiveAdmin.setup do |config|
  # == Friendly Id addon
  ActiveAdmin::ResourceController.class_eval do
    def find_resource
      if resource_class.is_a?(FriendlyId)
        scoped_collection.friendly.find(params[:id])
      else
        scoped_collection.find(params[:id])
      end
    end
  end
  # initial config
end

This looks much cleaner to me, than putting it in the application controller, as it is related to the configuration of Active Admin.

like image 23
Quentin Avatar answered Nov 04 '22 07:11

Quentin


Found solution for the problem:

In your app/admin/[ResourceName.rb] add:

  # app/admin/group.rb

  # find record with slug(friendly_id)
  controller do
    def find_resource
      begin
        scoped_collection.where(slug: params[:id]).first!
      rescue ActiveRecord::RecordNotFound
        scoped_collection.find(params[:id])
      end
    end
  end

This solved my problem.

like image 6
przbadu Avatar answered Nov 04 '22 05:11

przbadu