Abhi On Rails

Ruby On Rails - What I learned recently

Integrating FriendlyID, Inherited Reource and Active Admin

For my latest spare time project Kazhakkoottam I had to integrate friendly id with the app. But the application was already integrated and running with Inherited Resource and Active Admin. So while integrating with friendly id I have faced some issues.

So why we need to use friendly id?
FriendlyId is used to implement pretty URL's, so that it will be SEO friendly and can be identified easily. Instead of id's you can configure name or title field as the slug. For example http://www.kazhakkoottam.com/items/krishna-theatre is the friendly id for http://www.kazhakkoottam.com/items/1.

Integration issue with Inherited Resource
The first issue I faced was in the show page of an Item in ItemsController. ActiveRecord::RecordNotFound Couldn't find Item with id=lorem-ipsum. The reason is Inherited resource was using Item.find instead of Item.friendly.find()
Added the following code to the ItemsController to fix this issue:

    # app/controllers/items_controller.rb
    defaults resource_class: Item.friendly
  

Integration issue with Active Admin
Then I faced the same issue with Active Admin while accessed the show page of the item from Admin console. The solution was to add the following code to the active admin file for item.

      # app/admin/item.rb
      controller do
        def find_resource
          scoped_collection.friendly.find(params[:id])
        end
      end
    

Now I got the pretty URL integrated with my app which is SEO friendly and can be identified easily.

blog comments powered by Disqus
Active Admin - Custom Pages... →
← Active Admin tips and tricks