怎样用will_paginate对搜索结果进行分页?
我想用Rails的will_paginate插件来对搜索结果进行分页。
控制器如下:(只有两个action)
class CatalogController < ApplicationController
def index
@page_title="Book List"
@books=Book.paginate(:page=>params[:page], :per_page=>1)
end
def search
@page_title="Search"
if params[:commit]=="Search" || params[:q]
@books=Book.find_with_ferret(params[:q].to_s.upcase)
unless @books.size > 0
flash.now[:notice]="No books found matching your criteria"
end
end
end
end
在index这个action里,will_paginate能够很好地对Book模型进行分页。
index所对应的index.html.erb如下:
<h1>Listing books</h1>
<%=will_paginate @books %> # works well!
<table>
<tr>
<th>Title</th>
<th>Publisher</th>
<th>Published at</th>
<th>Isbn</th>
<th>Blurb</th>
<th>Page count</th>
<th>Price</th>
</tr>
<% @books.each do |book| %>
<tr>
<td><%=h book.title %></td>
<td><%=h book.publisher.name %></td>
<td><%=h book.published_at %></td>
<td><%=h book.isbn %></td>
<td><%=h book.blurb %></td>
<td><%=h book.page_count %></td>
<td><%=h book.price %></td>
<td><%= link_to 'Show', book %></td>
<td><%= link_to 'Edit', edit_book_path(book) %></td>
<td><%= link_to 'Destroy', book, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
接下来怎么样实现搜索结果的分页?
Search.html.erb如下:
<%=form_tag({:action=>"search"}, {:method=>"get"}) %>
<%=text_field_tag :q %>
<%=submit_tag "Search" %>
</form>
<% if @books %>
<%=will_paginate @books %> #没有效果
<p>Your search "<%=params[:q] %>" produced
<%=pluralize @books.size, "result" %>:</p>
<dl id="books">
<% for book in @books %>
<dt><%=link_to book.title, :action=>"show", :id=>book %></dt>
<% for author in book.authors %>
<dd><%=author.last_name %>, <%=author.first_name %></dd>
<% end %>
<dd><%=pluralize(book.page_count, "page") %></dd>
<dd>Price: $<%=book.price %></dd>
<dd><small>Publisher: <%=book.publisher.name %></small></dd>
<% end %>
</dl>
<% end %>
[解决办法]
根据错误提示检查你的字段,我只是举例,你要搜索字段是什么就替换什么.
q是你的表的字段名:
@books=Book.paginate :conditions => ["q = ?", params[:q].to_s.upcase]
[解决办法]