我正在尝试在我的Rails
应用程序上实现一个搜索功能,以使搜索框工作。
但是,在运行代码时,会引发以下错误:
NoMethodError in PostsController#index undefined method `paginate' for #<Searchkick::Results:0x007f3ff123f0e0>
(我还有一个标记云,如果我保持下面的代码不变,它可以正常工作,但是如果我将@posts = @posts
更改为@posts = Post.search
,它也会破坏标记功能。)
我正在使用:
- 导轨4.2.0
- ruby 2.2.1p85(2015年2月26日修订版49769)[x86_64-Linux]
代码:
下面是我的PostsController
的外观:
class PostsController < ApplicationController
before_action :find_post, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def new
@post = current_user.posts.build
end
def create
@post = current_user.posts.build(post_params)
if @post.save
redirect_to @post
else
render 'new'
end
end
def edit
@post = Post.friendly.find(params[:id])
end
def update
@post = Post.friendly.find(params[:id])
if @post.update(post_params)
redirect_to @post
else
render 'edit'
end
end
def destroy
@post.destroy
redirect_to root_path
end
def index
if params[:tag]
@posts = Post.tagged_with(params[:tag]).paginate(page: params[:page], per_page: 5)
else
@posts = Post.order('created_at DESC').paginate(page: params[:page], per_page: 2)
end
if params[:nil].present?
@posts = @posts.search(params[:nil]).paginate(page: params[:page])
else
@posts = @posts.paginate(page: params[:page])
end
end
def show
@post = Post.friendly.find(params[:id])
end
def autocomplete
render json: Post.search(params[:query], autocomplete: true, limit: 5).map(&:title)
end
private
def find_post
@post = Post.friendly.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :description, :content, :tag_list, :preview)
end
end
结束
这是我的导航栏搜索表单外观
<li class="navs">
<%= form_tag posts_path, method: :get do%>
<%= text_field_tag :search, params[:query], placeholder: "Search Blog", name: "nil" , required: "", class: "input-field", id: "post_search", autocomplete: "off" do %>
<%= submit_tag "", class: "material-icons search-box" %>
<% end %>
<% if params[:search].present? %>
<%= link_to "X", posts_path %>
<% end %>
<% end %>
</li>
我已经搜索了很多,但没有找到任何具体的答案,可以给我一个正确的方向,我做错了什么。
我真的很感激你的帮助。
2条答案
按热度按时间eoxn13cs1#
问题是
search
调用将返回一个Searchkick::Results
集合,而不是ActiveRecord::Relation
。后者已经用paginate
方法修补,而前者没有,因此引发了NoMethodError
。根据该文档,您应该能够通过将分页参数传递给
search
方法来实现此功能:quhf5bfb2#
除了在SeachKick查询中进行分页之外,您还可以在单独的步骤中执行以下操作。
@posts = Kaminari.paginate_array(@posts).page(params[:page])