Search code examples
ruby-on-railsfriendly-id

friendly_id url are not applying on pagination.


I am implementing friendly_id on a existing source code. The scenario is like this. There are category names on the home page. When user clicks on any one of these Categories link, it takes them to a page when it has products under that category. This page has pagination. The earlier url used to have category_id=number now after implementing friendly_id I got the url as category_id=name.

Old url:

localhost:3000/search?category_id=208

New url:

localhost:3000/search?category_id=name This url has pagination.

The issue is when I click on the 2nd page on this url it still has the same old url with id number like below.

localhost:3000/search?category_id=208&page=2

I know I am missing something. Could somebody please tell me how to fix this. Following is my controller. (Its freaking messy. Thats what happens when you try to implement new things on existing code.) Please check the end of the line where it has @equipments for pagination. Let me know if more information required.

controller

def search_equipments

    begin      
      if (params.keys & ['category_id', 'sub_category', 'manufacturer', 'country', 'state', 'keyword']).present?
        if params[:category_id].present?
          @category = Category.active.friendly.find_by_friendly_id params[:category_id]
        else
          @category = Category.active.friendly.find_by_friendly_id params[:sub_category] if params[:sub_category].present?
        end
        @root_categories = Category.active.roots
        @sub_categories = @category.children.active if params[:category_id].present?
        @sub_categories ||= {}
        @countries = Country.active.all
        @manufacturers = Manufacturer.active.all
        @states = State.active.where("country_id = ?", params[:country]) if params[:country].present?
        @states ||= {} 
        unless params[:category_id].present? && params[:sub_category].present?
          params[:category_id] = @category.id if params[:category_id].present?
          params[:sub_category] = @category.id if params[:sub_category].present?
        end   
        @equipments = Equipment.active.filter(params.slice(:manufacturer, :country, :state, :category_id, :sub_category, :keyword)).order("#{sort_column} #{sort_direction}, created_at desc").page(params[:page]).per(per_page_items)               
      else
        redirect_to root_path
      end
    rescue Exception => e
      render :file=>"#{Rails.root}/public/404.html",:status=>404
    end    
  end

Solution

  • If you're using kaminari, you should have something like the following in your view file that renders the page links/numbers:

    <%= paginate @equipments, params: request.query_parameters.merge(category_id: @category.slug) %>