0

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?

teddybear
  • 546
  • 2
  • 6
  • 14

1 Answers1

1

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, e. g. what should @next_image_id be if it's the last image and so on, but this should get you started.

panmari
  • 3,627
  • 3
  • 28
  • 48
  • Thank you. This has me goin in the right direction now. I'm getting a CookieOverflow error while trying to store the list to the session – teddybear Dec 18 '15 at 14:32
  • Yeah, you can't put too much information (such as full activerecord instances). I'd advise you to only save the ids there. I'll update my answer. – panmari Dec 18 '15 at 14:33
  • Thanks again. This is what I need for the most part. – teddybear Dec 18 '15 at 14:58
  • Side note: If I need to store multiple lists to session per user, can I do this without having to switch to active_record_store? Can I do this without going over the 4kb limit? – teddybear Dec 18 '15 at 15:04
  • Depends on how big your lists are... If there are multiple of the size of 10 then that shouldn't be a problem. – panmari Dec 18 '15 at 16:05
  • They are huge. I'm gonna try out localStorage http://railscasts.com/episodes/247-offline-apps-part-1?view=asciicast – teddybear Dec 18 '15 at 16:12