我正在使用meta_search
gem搜索目录中的产品。但是,当我第一次进入搜索页面或发送空白值时,就会进行搜索,并返回并列出所有产品。
我试图防止检查搜索输入的值不是nil
或""
,因此只有在文本字段中实际键入内容时才执行搜索。
这是我的search.html.erb
文件:
<%= render :partial => 'search_box' %>
<% if @products %>
<p>The search "<%= params[:search][:name_contains] %>" returned <%= pluralize @products.size, "result" %>:</p>
<%= render(:partial => "products") %>
<% end %>
_search_box.html.erb
:
<%= form_for @search, :url => "/catalog/search", :html => {:method => :get} do |f| %>
<%= f.label :Name %>
<%= f.text_field :name_contains %>
<%= f.submit 'Search' %>
<% end %>
CatalogController
:的search
方法
def search
if params[:search]
@search = Product.search(params[:search])
@products = @search.all
unless @products.size > 0
flash.now[:notice] = "No results"
end
end
end
当我浏览到/catalog/search
时,我得到以下错误:
NoMethodError in Catalog#search
Showing /*****/app/views/catalog/_search_box.html.erb where line #1 raised:
undefined method `model_name' for NilClass:Class
Extracted source (around line #1):
1: <%= form_for @search, :url => "/catalog/search", :html => {:method => :get} do |f| %>
2: <%= f.label :Nombre %>
3: <%= f.text_field :name_contains %>
4: <%= f.submit 'Search' %>
试试这个,我认为这样你的@搜索就会一直找到
def search
@search = Product.search(params[:search])
if params[:search]
@products = @search.all
flash.now[:notice] = "No results" unless @products.size > 0
end
end