ActiveRecord::ReadOnlyRecord when using ActiveAdmin and Friendly_id

前端 未结 5 1960
梦如初夏
梦如初夏 2020-12-08 16:36

I started using ActiveAdmin recently in a project and almost everything works great but I\'m having a problem when using it in combination with the friendly_id gem. I\'m ge

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 17:18

    You can customize the resource retrieval according to http://activeadmin.info/docs/2-resource-customization.html#customizing_resource_retrieval. Note that you want to use the find_resource method instead of resource, or you won't be able to create new records.

    (Check https://github.com/gregbell/active_admin/blob/master/lib/active_admin/resource_controller/data_access.rb for more details)

    In your ActiveAdmin resource class write:

    controller do
      def find_resource
        scoped_collection.where(slug: params[:id]).first!
      end
    end
    

    You can also overwrite the behavior for all resources by modyfing the ResourceController in the active_admin.rb initializer.

    ActiveAdmin::ResourceController.class_eval do
      def find_resource
        if scoped_collection.is_a? FriendlyId
          scoped_collection.where(slug: params[:id]).first! 
        else
          scoped_collection.where(id: params[:id]).first!
        end
      end
    end
    

    Hope that helps!

    Side note: When creating new records through the admin interface make sure you don't include the slug field in the form, or FriendlyId will not generate the slugs. (I believe that's for version 5+ only)

提交回复
热议问题