I have a method that sorts the index for a list of products. Sorts them alphabetically, by rating, etc. That works perfect.
When I got to the show page, I added next and previous buttons. But they are working off the next ID in the table, not the next in the sort I made. I think as a user, I want to cycle through my currently chosen sort.
So I changed the next/previous methods to get the index of the current show product, next will add +1, previous -1 to the index and check the length -1 to start it back to zero.
But here's the issue. I need to preserve the current variable of the sort for the next/previous methods to access.
The approach I'm trying: I think I need to use after_action on the controller to set the variable aside in a method. The index method contains the used sort variable something like:
after_action :set_product_sort, only: [:index]
private
def set_product_sort
@current_product_sort = @products_sort
end
From research, I keep seeing i have to involve the routes. Something like this:
resources :products_controller do
collection do
get :set_product_sort
end
end
So if that makes sense (I'm out of my depth here). I am not clear on a few things.
If I do before_action on the index method, the variable will not be set to the sort. So I think after_action is what I need. But am I wrong? Will the variable already be dropped at that point?
In that routes block, what is "collection". I got that block from a blog post and trying to look up "collection" yields general info about collections. I am thinking perhaps collection is supposed to be the variable name (ie @products_sort)?
And finally, how would I call upon this next/previous Next/previous need to know the current product as well as the current sort. The current product is already in the controller show method. Does that routes.rb block set the sort variable up to just call it in method? or does it need to be dot notation and maybe make the next/previous self.next and self.previous?
products_path(page: 2)->/products?page=2Then in your index compute the offset based of the page.Product.where(...).order(...).offset(params[:page].to_i * 20)(0 based page number, 20 records per page). There are a some gems out there that simplify pagination.