Rails will_paginate错误:undefined method `total_pages'

5

users_controller.rb:

@search_results = Notice.search('hello')
if(params[:query])
  @search_results = Notice.search(params[:query])
end

Notice.rb:

def self.search(search)
  if search
    Notice.where("content LIKE ?", "%#{search}%")
  else
  end
end

在视图中:

<%= render 'shared/search_results' %>

_search_results.html.erb局部文件:

<% if @search_results.any? %>
  <ol class="notices">
    <%= render @search_results %>
  </ol>
  <%= will_paginate @search_results %>
<% end %>

我遇到了错误:#<Notice::ActiveRecord_Relation:0x0000010f3e8888>没有定义total_pages方法。

(没有分页时一切正常。)

我该如何修复这个错误?


你需要在控制器中对你的集合调用 .paginate 方法: @search_results = @search_results.paginate(page: params[:page], per_page: 20) - MrYoshiji
2个回答

7

来自will paginate文档:

## perform a paginated query:
@posts = Post.paginate(:page => params[:page])

# or, use an explicit "per page" limit:
Post.paginate(:page => params[:page], :per_page => 30)

## render page links in the view:
<%= will_paginate @posts %>

所以,对于你的代码,你需要做以下操作:
search_results = Notice.search('hello').paginate(page: params[:page])
if(params[:query])
  @search_results = Notice.search(params[:query]).paginate(page: params[:page])
end

或者是 ActiveRecord 3 中的新语法

search_results = Notice.search('hello').page(params[:page])
if(params[:query])
  @search_results = Notice.search(params[:query]).page(params[:page])
end

0

当我在开发一个Rails 6应用程序时,我也遇到了同样的挑战。

这是我的代码:

def index
  if params[:query].present?
    @products = Product.search(params[:query])
  else
    @products = Product.paginate(page: params[:page], per_page: 30)
  end
  @brands = Brand.all
  @categories = Category.all
end

每当我尝试搜索产品时,它就会抛出以下错误: undefined method `total_pages' for #Product::ActiveRecord_Relation:0x00007f1f802423d0
以下是我如何解决的:
我只需在if语句中也添加paginate方法即可:
paginate(page: params[:page], per_page: 30)

于是,我的代码在那之后看起来像这样:

def index
  if params[:query].present?
    @products = Product.search(params[:query]).paginate(page: params[:page], per_page: 30)
  else
    @products = Product.paginate(page: params[:page], per_page: 30)
  end
  @brands = Brand.all
  @categories = Category.all
end

就这些了。

希望这能有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接