Search code examples
ruby-on-railssearchcontrollerpaginationwill-paginate

Rails pagination does not load content for second page for search results


I have a method to get the search result and show and it is working fine. But, whenever I try to go to second page, it says error regarding no content.

Here is my controller code:

class BuyersController < UsersController

def show
end

def search
end

def search_products
    search_name = params[:search][:name]
    search_category = params[:search][:category_id].to_i
    search_location_id = params[:search][:location_id].to_i
    search_highest_bid = params[:search][:highest_bid].to_f
    @matching_products = ProductsUnderBid.search_products_under_bid(name: search_name, category_id: search_category, 
                                                                    location_id: search_location_id, highest_bid: search_highest_bid)
    @matching_products = @matching_products.paginate(page: params[:page], per_page: 1)
end
end

Solution

  • I changed the methods like below and it worked! As you can see, I cahnged the variable types to global in search_products method so that I can access it from show method.I also had to add show.html.erb under the in app/view/controller_name/ folder. Hope it helps others.

    def show
        @matching_products = ProductsUnderBid.search_products_under_bid(name: $search_name, category_id: $search_category, 
                                                                                location_id: $search_location_id, highest_bid: $search_highest_bid)
        @matching_products = @matching_products.paginate(:page => params[:page],:per_page => 5)
                get_already_placed_bids(@matching_products)
    end
    
    def search_products
        $search_name = params[:search][:name]
        $search_category = params[:search][:category_id].to_i
        $search_location_id = params[:search][:location_id].to_i
        $search_highest_bid = params[:search][:highest_bid].to_f
        @matching_products = ProductsUnderBid.search_products_under_bid(name: $search_name, category_id: $search_category, 
                                                                        location_id: $search_location_id, highest_bid: $search_highest_bid)
        @matching_products = @matching_products.paginate(:page => params[:page],:per_page => 5)
        get_already_placed_bids(@matching_products)
    end