我想要一个数据搜索功能。搜索后,按列排序,然后将结果限制在200以内。最后用will_pagenate分页。
我的控制器
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
我的型号
def self.search(标题、公司、位置id、页面)如果location_id.spresent?
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
结束
为了限制结果,我尝试更改为以下代码:
paginate :conditions => ['title LIKE ? AND company LIKE ?', "%#{title}%", "%#{company}%"].limit(200)
但它不起作用。最好的方法是什么?
在您的模型中
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
或者,您可以将"total_entries"传递给分页方法,如图所示:
wages = Wage.where('title LIKE ? AND company LIKE ? AND location_id = ?', "%#{title}%", "%#{company}%", location_id).order('total DESC').paginate(:page => page, :total_entries => 200)
我希望这能有所帮助。
用另一个问题检查结果的页码限制似乎可以这样做:
wages = Wage.limit(100).paginate(:per_page => 5)
在你的情况下(我还没有测试过,但我认为它可以工作):
@wages = Wage.where('title LIKE ? AND company LIKE ?', "%#{title}%", "%#{company}%").limit(200).paginate(:per_page => 20, :order => "total DESC", :page => page)
在这种情况下,@wages
是will_paginate
对象:
@wages.total_pages
=> 20
也可以使用视图中will_paginate
的html_helpers
进行渲染(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' %>