Rails will_paginate错误:未定义的方法`total_pages'

Baz*_*ley 3 ruby-on-rails

users_controller.rb:

@search_results = Notice.search('hello')
if(params[:query])
  @search_results = Notice.search(params[:query])
end
Run Code Online (Sandbox Code Playgroud)

Notice.rb:

def self.search(search)
  if search
    Notice.where("content LIKE ?", "%#{search}%")
  else
  end
end
Run Code Online (Sandbox Code Playgroud)

在视图中:

<%= render 'shared/search_results' %>
Run Code Online (Sandbox Code Playgroud)

_search_results.html.erb部分:

<% if @search_results.any? %>
  <ol class="notices">
    <%= render @search_results %>
  </ol>
  <%= will_paginate @search_results %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

我收到错误:undefined method total_pages for #<Notice::ActiveRecord_Relation:0x0000010f3e8888>.

(这一切都很好,没有分页.)

我该如何解决这个错误?

Lui*_*aca 6

从遗嘱paginate文档:

## perform a paginated query:
@posts = Post.paginate(:page => params[:page])

# or, use an explicit "per page" limit:
Post.paginate(:page => params[:page], :per_page => 30)

## render page links in the view:
<%= will_paginate @posts %>
Run Code Online (Sandbox Code Playgroud)

因此,对于您需要执行的代码:

search_results = Notice.search('hello').paginate(page: params[:page])
if(params[:query])
  @search_results = Notice.search(params[:query]).paginate(page: params[:page])
end
Run Code Online (Sandbox Code Playgroud)

或ActiveRecord 3中的新语法

search_results = Notice.search('hello').page(params[:page])
if(params[:query])
  @search_results = Notice.search(params[:query]).page(params[:page])
end
Run Code Online (Sandbox Code Playgroud)