Bill C. wrote:
I am trying to do a simple search by product name. The first page
returns fine, but when I try to go to any other pages of the search
results, I lose the original search parameters from my search form and
get NilClass errors.
Here is the code in my controller:
namesearch = “%” + params[:name].strip + “%”
@product_pages, @products = paginate :product,
:conditions => [“product_name like :name”, {:name =>
namesearch}],
:per_page => 10
This seems like it should be a very common task and I assumed RoR would
handle it automatically by adding the original search parameters to the
pagination links. Is there a correct way to accomplish a multi-page
search that uses conditions?
I’ve made a little progress on this by using merge_params in my view.
For the paginate links I changed the line
pagination_links( @@product_pages )
to:
pagination_links( @product_pages, :params => @params.merge (:a =>“1”))
(I found I needed to add the dummy variable “a” in order to make it
work)
Anyway, this gets me a step closer, but it still does not work properly.
It adds the fields from my original search and I am able to click on
another page after page 1 of the search result, but it end there. If I
click on page two, “page” is added as a param, and all future pagination
links have “page=2” added to them so every link points to page 2.
Also, even if I could get this to work correctly, I am unsure of how to
add the “@params.merge” to the previous and next links.
I am hoping someone can point me in the right direction here. My
experience with rails has been that if I need to work this hard on
something so simple, I am probably missing an easier way to do it. It’s
hard for me to imagine that the pagination stuff only works when listing
the entire contents of a table, and can’t handle user defined searches
from a form field.