Reputation: 325
I'm trying to create links to navigate through an array. I have three classes: fsets, line_items, and exemplars.
In my app I have it so on a page a user is shown an image. I want the user to be able to click a next/previous link to go to the next element in the array. I can currently display all the images on the page but can't find out how to create the next/previous links. Elsewhere in the app I have used the following to go to the next record in the db but can't figure out how to implement the same for the array.
def previous
Exemplar.where(["id < ?", id]).last
end
def next
Exemplar.where(["id > ?", id]).first
end
I was hoping that if I could return the index position in the array I could link_to the next one but I can't figure out how to do that. I started by displaying the current position of the element and the previous/next positions.
next: <%= (params[:pos].gsub(/\D/, '').to_i + 1) %>
current: <%= params[:pos].gsub(/\D/, '').to_i %>
previous: <%= (params[:pos].gsub(/\D/, '').to_i - 1) %>
I am passing the index position of each element in the params using the :pos. So when the page first loads the :pos is set to 0. There are links on the bottom of the page allowing the user to jump to items in the array. Those links pass the index position as well. I know there is an easier way to do all this and I've gone down the wrong path/way of thinking about all of this. Just thought it would be helpful to show what I've tried even if completely wrong.
Upvotes: 0
Views: 134
Reputation: 6095
This gem will do what you need. https://github.com/mislav/will_paginate
If you can link to your github i might be able to help more. You will want to extract that pagination logic out to somewhere that is not the activerecord model.
Upvotes: 2