Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails will_paginate error: undefined method `total_pages'

users_controller.rb:

@search_results = Notice.search('hello')
if(params[:query])
  @search_results = Notice.search(params[:query])
end

Notice.rb:

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

In the view:

<%= render 'shared/search_results' %>

_search_results.html.erb partial:

<% if @search_results.any? %>
  <ol class="notices">
    <%= render @search_results %>
  </ol>
  <%= will_paginate @search_results %>
<% end %>

I get the error: undefined method total_pages for #<Notice::ActiveRecord_Relation:0x0000010f3e8888>.

(It all works fine without pagination.)

How do I fix this error?

like image 940
Bazley Avatar asked Apr 21 '15 16:04

Bazley


1 Answers

From the will paginate documentation:

## 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 %>

So, for your code you need to do:

search_results = Notice.search('hello').paginate(page: params[:page])
if(params[:query])
  @search_results = Notice.search(params[:query]).paginate(page: params[:page])
end

or the new Syntax in ActiveRecord 3

search_results = Notice.search('hello').page(params[:page])
if(params[:query])
  @search_results = Notice.search(params[:query]).page(params[:page])
end
like image 136
Luis D Urraca Avatar answered Nov 14 '22 23:11

Luis D Urraca