Search code examples
ruby-on-railskaminari

On deleting the last record on page 2, navigate user back to page 1


I'm using Kaminari Gem on my rails apps.

I have the current index page with proper navigation menus.

def index
  @dogs = Dog.all.page(params[:page]).per(20)
end


def destroy
  if @dog.destroy
    # use this so that if the page got other records, the user got to stay at that navigated page.
    redirect_back fallback_location: dogs_path, flash: { success: 'deleted dog from list' }
  else
    # show some errors
  end
end

When user is at page 2 and deleting the 21st dog record, the record got deleted and the browser is showing a blank page with no record cause the url is specifying /dogs?page=2.

Is this the default behavior or Kaminari or I have something wrong on my method? I was expecting Kaminari to redirect the user to 1 page before since current page is not containing any records.

Thanks.


Solution

  • Consider you have dogs index page path as dogs_path

    def destroy
      if @dog.destroy
        page = params[:page]
        #this is to check if we have more elements on the page or not
        @dogs = Dog.all.page(page).per(20)
        if @dogs.length == 0 
          page = (page - 1) > 1 ? page - 1 : 1  
        end
        redirect_to dogs_path(page: page)
      else
        # show some errors
      end
    end