Ruby on Rails搜索框搭配分页无结果显示及报错问题求助
Hey there! Let's get this pagination issue sorted out for you. The error you're seeing happens because when you perform a search, your @products collection isn't being paginated, but will_paginate expects a paginated ActiveRecord Relation to work correctly.
Here's the Problem in Your Code
Looking at your ProductsController#index action:
- When there's no search term (
elsebranch), you correctly call.paginate(page: params[:page], per_page: 6)onProduct.all - But when a search term is present, you just assign
@products = Product.search(search_term)— this returns a plain ActiveRecord Relation without pagination applied, which causeswill_paginateto throw an error.
The Fix: Apply Pagination to Both Cases
You need to ensure pagination is applied regardless of whether a search is being performed. Here's how to update your controller:
Option 1: Explicitly Paginate in Both Branches
def index if params[:q] search_term = params[:q] # Add .paginate to the search result @products = Product.search(search_term).paginate(page: params[:page], per_page: 6) else @products = Product.all.paginate(page: params[:page], per_page: 6) end end
Option 2: DRYer Version (Combine Logic)
You can refactor to avoid repeating the pagination code:
def index @products = if params[:q] Product.search(params[:q]) else Product.all end.paginate(page: params[:page], per_page: 6) end
Bonus: Ensure Search Params Persist in Pagination Links
Great news — will_paginate automatically preserves existing query parameters (like your q search term) in the pagination links, so when users navigate between pages after a search, the search term stays active.
Quick Check of Your Search Method
Your model's search method is returning an ActiveRecord Relation (thanks to the where clause), which is perfect because it lets us chain the paginate method onto it. No changes needed there!
That should resolve the error and make pagination work seamlessly with both your default product list and search results.
内容的提问来源于stack exchange,提问作者Andreia

