2016-09-16 55 views
0

我是RoR的新手,我正在上一门课程。我已经实现了ActiveRecord查询以及will_paginate gem,两者都可以单独工作。ActiveRecord查询在添加分页时停止工作| Rails 5 |

然而,当我增加了分页功能,查询搜索断裂,给我以下错误:

NoMethodError在产品#指数 未定义的方法`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> 

回答

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")看起来有点腥:)

+0

谢谢你的片段。代码看起来更清洁这种方式比我原来的更正:) – catch22

1

那是因为你还没有加入paginate调用@products = ...任务,从而得到所谓当有是一个搜索词。对paginate的这种调用是将total_pages方法添加到集合中,否则你只是处理一个正常的(即非分页的)ActiveRecord集合。