加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 使用Kaminari Pagination Gem进行简单搜索

发布时间:2020-12-17 03:47:18 所属栏目:百科 来源:网络整理
导读:我正在尝试使用Kaminari将分页应用到我的rails应用程序.我还整合了一个基于 Railscast Episode #37的简单搜索表单.当我尝试应用kaminari页面和每个方法时,我得到错误’未定义的方法页面’.下面是我正在使用的代码. posts_controller.rb def index @posts = P
我正在尝试使用Kaminari将分页应用到我的rails应用程序.我还整合了一个基于 Railscast Episode #37的简单搜索表单.当我尝试应用kaminari页面和每个方法时,我得到错误’未定义的方法页面’.下面是我正在使用的代码.

posts_controller.rb

def index
  @posts = Post.search(params[:search]).page(params[:page]).per(2)
end

post.rb

def self.search(search)
  if search
    find(:all,conditions: ['title || body LIKE ?',"%#{search}%"],order: "created_at DESC")
  else
    find(:all)
  end
end

index.html.erb

<%= paginate @posts %>

当我删除分页时,搜索工作正常.当我删除搜索时,分页工作正常.我似乎无法使用它们并使代码正常运行.请告知我的代码中是否存在我遗漏的导致此操作无法正常工作的内容.

解决方法

在您的情况下,您从搜索方法返回数组对象而不是ActiveRecord :: Relation对象.

find(:all,conditions: ...) # find method will return an array object.

添加检查控制器,

def index
  @posts = Post.search(params[:search])
  if @posts.class == Array
    @posts = Kaminari.paginate_array(@posts).page(params[:page]).per(10) 
  else
    @posts = @posts.page(params[:page]).per(10) # if @posts is AR::Relation object 
  end
end

Kaminari与阵列https://github.com/amatsuda/kaminari#paginating-a-generic-array-object分页

对于ActiveRecord :: Relation对象,请查看此http://railscasts.com/episodes/239-activerecord-relation-walkthrough

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读