注:rails的版本是2.0以上.
1.在application.rb里添加分页信息方法:
1 def page_for(result,options={})
2
3 default_options = {:per_page => 10}
4 options = default_options.merge options
5 pages = WillPaginate::Collection.new(options[:page],options[:per_page],result.total_hits)
6 return pages
7
8 end
2.users_controller.rb里添加search方法:
1 def search
2
3 @keyWord=params[:keyWord]
4 if params[:page]==nil||params[:page]==""
5 @page=1
6 else
7 @page=params[:page]
8 end
9 @users=User.find_by_contents(@keyWord,:per_page=>2,:page=>@page)
10 @pages=page_for(@users,:page=>@page,:per_page=>2)
11 end
3.view页面:
1 <%@users.each do |user|%>
2 <br>
3 username: <%=user.highlight(@keyWord,:field=>:user_name,:num_excerpts=>1,:pre_tag=>'<strong>',:post_tag=>'</strong>')%><br>
4 地址:<%=user.highlight(@keyWord,:field=>:introduce,:num_excerpts=>1,:pre_tag=>'<strong>',:post_tag=>'</strong>')%>
5 ==================================================================================
6 <%end%>
7 <p>
8 共<%=@users.total_hits%>条记录
9 </p>
10 <p>
11 <%=link_to "上一页",{:page=>@pages.previous_page,:keyWord=>@keyWord} %>
12 <%=link_to "下一页",{:page=>@pages.next_page,:keyWord=>@keyWord} %>
13 <br/>
14 <%=will_paginate @users%>
15 </p>