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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With