ruby-on-rails - 如何修复“未定义的方法 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'
我理解这个错误,因为添加了分页,但不知道如何克服这个问题。
解决方案
也许问题不是你的分页,而是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
推荐阅读
- java - SPRING-BATCH 错误:没有可用于步骤范围的上下文持有者
- c++ - C ++在第一类实例中创建第二类实例并将第一类作为参数传递
- wordpress - 谷歌搜索中的 Wordpress 错误:显示已删除的恶意软件目录
- dataframe - DataFrames.jl :在定义计数列名称时按组计数行
- node.js - MongoDB 是否需要我在 shell 中手动运行 mongod?
- ruby-on-rails - 如何在 Rails 6 中使用 Postgres 区间数据类型
- drupal-8 - 我可以使用哪个钩子以编程方式更新 drupal 商务中的产品?
- javascript - firebase.auth.GoogleAuthProvider.credential 未定义
- java - 二叉树最大路径和算法
- swift - Swift UI DatePicker 不会更新 @ObservedObject 值