Tab Codes
Tab Codes

Reputation: 33

will_paginate giving an error when doing a search

Alrighty, so I have searched on here repeatedly on this as well as other places but have yet to find the solution that relates to me. Probably because the previous questions were some time ago.

My problem is that I had first added pagination and then I was required to add a search so that users could search for products. When they do the search it's just supposed to open the products page. If I took out the search, the pagination doesn't give me an error.

The error I get now is

''undefined method `total_pages' for # Product::ActiveRecord_Relation:''

and the line of code highlighted for the error is the pagination in the index.html.erb.

What am I missing? Thanks for any guidance, this newbie needs it!

This is the products_controller:

  def index
   if Rails.env == "development"
    name_env = "name LIKE ?"
   else
    name_env = "name ilike ?"
   end
   if params[:q]
    search_term = params[:q]
    @products = Product.search(search_term)
   else
    @products = Product.all
    @products = Product.paginate(:page => params[:page], per_page: 4)
   end
  end

This is the index.html.erb :

  <div class="pagination">
   <%= will_paginate @products %>
  </div>

Upvotes: 0

Views: 109

Answers (2)

Ganesh
Ganesh

Reputation: 2004

Modify index action as follows:

def index
    if Rails.env == "development"
        name_env = "name LIKE ?"
    else
        name_env = "name ilike ?"
    end
    @products = params[:q] ? Product.search(params[:q]) : Product.scoped
    @products.paginate(:page => params[:page], per_page: 4)
end

you should use paginate for searching too.

Upvotes: 0

fool-dev
fool-dev

Reputation: 7777

You have missed paginate method when the search, it @products = Product.search(search_term) will be like this

.....
if params[:q]
    search_term = params[:q]
    @products = Product.search(search_term).paginate(:page => params[:page], per_page: 4)
else
    @products = Product.all.paginate(:page => params[:page], per_page: 4)
.....

Additionally Remove this @products = Product.all don't need this.

After all, you just paste this instead of your code, it reduced

def index
   if Rails.env == "development"
    name_env = "name LIKE ?"
   else
    name_env = "name ilike ?"
   end
   if params[:q]
    search_term = params[:q]
    @products = Product.search(search_term)
   else
    @products = Product.all
   end
   @products = @products.paginate(:page => params[:page], per_page: 4)
end

Upvotes: 1

Related Questions