Hi there everyone, I’ve recently moved to RoR and am still struggling
with the basics of what used to be second nature in php, so on with
my question:
I have a database with products, and I need to create a search form
that paginates the results. What I have so far in my controller is:
def list
# If the values are nil, then set them, otherwise wrap them in %
# Also, set up our view instance variable, to re-populate the
search form
@view = Machine.new
@view.make = getParam("make")
@view.model = getParam("model")
# Search the database and populate our paging object
@filtered_machines = Machine.find(:all, :conditions => ["make
LIKE ? AND model LIKE ? AND for_sale = 1 AND web_width != 0",
sqlWildcard(@view.make),
sqlWildcard(@view.model)])
@machine_pages, @machines = paginate_collection(@filtered_machines)
end
def getParam(name, default="")
params.fetch(“view”, {}).fetch(name, default)
end
def sqlWildcard(value)
value.blank? ? ‘%’ : “%#{value}%”
end
Now, the list page is a full listing, and it has a filter box at the
top that people can type in and hit Filter and it searches ad returns
a cut down version. But what I have in my view paginates the
results, but the links to other pages drop the search. I’ve probably
not done this the right way, I’m open to suggestions on best
practises etc. Here’s my view:
<%= render :partial => ‘search’ %>
<%= link_to ‘Previous page’, { :page =>
@machine_pages.current.previous } if @machine_pages.current.previous %>
<%= link_to ‘Next page’, { :page =>
@machine_pages.current.next, :make => @view.make, :model =>
@view.model } if @machine_pages.current.next %>
<%= render :partial => “machine”, :collection => @machines %>
Everything works apart from the pagination. But again, this feels a
little messy, so please feel free to rip apart the way I’ve done it.
Thanks,
Jamie van Dyke
Fear of Fish