简体   繁体   中英

Jump to page using Kaminari Gem

I am trying to add pagination after a item from a paginated list is linked to. I can't seem to find a way to do this or find the answer. I am trying to display a list of images on a page, what I am trying to do is, when an image is clicked the user would go to that individual image page and then on the page there would be "Next" link to the next image in the list. So, say I have a list of images in this order [1, 5, 3, 6, 4, 7, 8, 2, 9, 10 ] display 5 per page. The user clicks image with id: 5 (position 1 in the list) and gets taken to '/images/5'. How do I add a link to the next image in this list (id: 3) and so on from there?

In the images controller

def index
  @list = Images.first(10).shuffle
  @images = Kaminari.paginate_array(@list).page(params[:page]).per(5)
end

What would I need in the corresponding views as well?

You'd have to remember the order in which the images were shuffled before. You could for example save this in the session

def index
  @list = Images.first(10).shuffle
  session[:image_list] = @list.map(&:id)
  @images = Kaminari.paginate_array(@list).page(params[:page]).per(5)
end

Then when showing one image, you could look up the index of the shown image in session[:image_list] and save the id of the next image in an instance variable

def show
  idx = session[:image_list].index(shown_image_id)
  @next_image_id = session[:image_list][idx + 1]
  # Do some more stuff for showing image
end

Use then @next_image_id to create a link to the next image. There are still some tricky bits left to do, eg what should @next_image_id be if it's the last image and so on, but this should get you started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM