Reputation: 203
I want to have a search function for the data. After search, then order by a column and then limit the results to 200 only. Finally paginate with will_paginate.
My Controller
def search
title = params[:title]
company = params[:company]
location_id = params[:location_id]
page = params[:page]
@wages = Wage.search(title, company, location_id,page)
end
My model
def self.search(title, company, location_id, page) if location_id.present?
paginate :conditions => ['title LIKE ? AND company LIKE ? AND location_id = ?', "%#{title}%", "%#{company}%", location_id],
:order => "total DESC",
:page => page,
:per_page => 20
else
paginate :conditions => ['title LIKE ? AND company LIKE ?', "%#{title}%", "%#{company}%"],
:order => "total DESC",
:page => page,
:per_page => 20
end
end
I tried changing to the below code in order to limit the result:
paginate :conditions => ['title LIKE ? AND company LIKE ?', "%#{title}%", "%#{company}%"].limit(200)
But it is not working. What is a best way to do it?
Upvotes: 0
Views: 2529
Reputation: 6238
Checking with this other question will-paginate-limit-number-of-results seems that you can do something like this:
wages = Wage.limit(100).paginate(:per_page => 5)
In your case (I haven't tested it, but I think that it can work):
@wages = Wage.where('title LIKE ? AND company LIKE ?', "%#{title}%", "%#{company}%").limit(200).paginate(:per_page => 20, :order => "total DESC", :page => page)
In this case @wages
is a will_paginate
object:
@wages.total_pages
=> 20
Or you can render with the html_helpers
of will_paginate
in the view (API-documentation#view-template-helpers).
# controller
@wages = Wage.where('title LIKE ? AND company LIKE ?', "%#{title}%", "%#{company}%").limit(200)
# you should have @wages.count = 200
# view
<%= will_paginate @wages, :style => 'color:blue' %>
Upvotes: 0
Reputation: 2941
In your model
class Wage < ActiveRecord::Base
self.per_page = 10
def self.search(title, company, location_id, page)
if location_id
wages = Wage.where('title LIKE ? AND company LIKE ? AND location_id = ?', "%#{title}%", "%#{company}%", location_id).order('total DESC').limit(200).paginate(:page => page)
else
wages = Wage.where('title LIKE ? AND company LIKE ?', "%#{title}%", "%#{company}%").order('total DESC').limit(200).paginate(:page => page)
end
return wages
end
end
Alternatively, you can pass in "total_entries" to your paginate method, as shown:
wages = Wage.where('title LIKE ? AND company LIKE ? AND location_id = ?', "%#{title}%", "%#{company}%", location_id).order('total DESC').paginate(:page => page, :total_entries => 200)
I hope this helps.
Upvotes: 0