You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails搜索框搭配分页无结果显示及报错问题求助

Fixing Pagination Error After Adding Search in Rails Product List

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 (else branch), you correctly call .paginate(page: params[:page], per_page: 6) on Product.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 causes will_paginate to 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

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:09:30