【问题标题】:ActiveRecord querying stops working when adding pagination | Rails 5 |添加分页时 ActiveRecord 查询停止工作 |导轨 5 |
【发布时间】:2017-01-24 12:26:59
【问题描述】:

我是 RoR 的新手,我正在在线学习课程。我已经实现了 ActiveRecord 查询以及 will_paginate gem,并且两者都可以单独工作。

但是,在我添加分页后,查询搜索中断并出现以下错误:

产品中的 NoMethodError#index #

的未定义方法“total_pages”
Extracted source (around line #7):

<div class="container-fluid">
    <div class="pages">
     <%= will_paginate @products %>
</div>

  <div class="row">

Gemfile

gem 'will_paginate'

products_controller.rb

def index
  if params[:q]
    search_term = params[:q]
    if (Rails.env == "production")
      @products = Product.where("name ilike ?", "%#{search_term}%")
    else
      @products = Product.where("name LIKE ?", "%#{search_term}%")
    end
  else
    @products = Product.all.paginate(:page => params[:page], :per_page => 3)
  end
end

 private
    # Use callbacks to share common setup or constraints between actions.
    def set_product
      @product = Product.find(params[:id])
    end

application.html.erb

<li class="nav-search">
  <%= form_tag("/products", method: "get") do %>
    <%= text_field_tag(:q) %>
    <%= submit_tag("Go!", class: 'button-s') %>
  <% end %>
</li>

【问题讨论】:

    标签: ruby-on-rails activerecord pagination


    【解决方案1】:

    这是因为,当 params[:q] 存在时,分页没有打开。 我会按照这些思路做一些事情:

    def index
      @products = find_products.paginate(:page => params[:page], :per_page => 3)
    end
    
    private
    
    def find_products
      if params[:q]
        search_term = params[:q]
        if (Rails.env == "production")
          Product.where("name ilike ?", "%#{search_term}%")
        else
          Product.where("name LIKE ?", "%#{search_term}%")
        end
      else
        Product.all
      end
    end
    

    不过,if (Rails.env == "production") 看起来有点可疑 :)

    【讨论】:

    • 感谢您的 sn-p。这样代码看起来比我原来的更正更干净:)
    【解决方案2】:

    这是因为您没有将 paginate 调用添加到当有搜索词时调用的 @products = ... 分配。这个对 paginate 的调用是将 total_pages 方法添加到集合中,否则您只是在处理普通的(即未分页的)ActiveRecord 集合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 2012-01-08
      • 2013-05-16
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 2015-10-27
      相关资源
      最近更新 更多