首页 > 解决方案 > 如何修复“未定义的方法 total_pages”

问题描述

我正在我的 Ruby On Rails 应用程序中设置搜索功能。我希望用户搜索特定主题并能够显示结果。但是,如果没有待处理的结果,它应该显示验证。

我目前已尝试研究和添加不同的代码,例如添加@topic.paginate(:page => 1, :per_page => 2)

试试这个:

Topic.tagged_with(params[:tag]).order(created_at: :desc).page(params[:page]).per(3)

主题控制器:

def index
 if params[:search].present?
   @topics = Topic.search(params[:search]).paginate(:page => params[:page], :per_page => 5)
   flash[:notice] = "No records found based on the search." if @topics.blank?
 else
   @topics = Topic.all
   flash[:notice] = "No records found in Database." if @topics.blank?
 end
end

index.html.erb:

<div> <%= will_paginate @topic, renderer: BootstrapPagination::Rails %> </end>

我希望作为验证消息出现。但是,我有以下错误:

**未定义的方法`total_pages'

错误截图

我理解这个错误,因为添加了分页,但不知道如何克服这个问题。

标签: ruby-on-railssearchwill-paginate

解决方案


也许问题不是你的分页,而是else你没有分页的分支@topics。Will_paginate 无法创建分页链接。

def index
  if params[:search].present?
    @topics = Topic.search(params[:search]).paginate(:page => params[:page], :per_page => 5)
    flash[:notice] = "No records found based on the search." if @topics.blank?
  else
    @topics = Topic.all.paginate(:page => params[:page], :per_page => 5) #add this
    flash[:notice] = "No records found in Database." if @topics.blank?
  end
end

推荐阅读