如果不存在搜索产品,则显示消息“未找到产品”,在ruby中

时间:2015-07-14 07:19:17

标签: ruby-on-rails search

如果数据库中没有产品,我想显示未找到的产品。如何在products_controller.rb 其他条件中获取此内容?

application.html

<div class="input-group search-block">
    <%= form_tag products_path, :method => "get",:validate => true, html: {class: "navbar-form navbar-left form-width col-xs-6"} do %>
    <div class="input-append">
    <%= text_field_tag :search, params[:search],  placeholder: "Search Products" , class: "form-control" %>
    <div class="input-group-btn">
    <button class="btn btn-info home_searchbar_btn" type="submit"><span class="fa fa-search"></span></button>
    </div></div>
    <% end %> 
</div>

products_controller.rb

def index
  @products = Product.all
  if params[:search]
     @products = Product.search(params[:search]).order("created_at DESC")
  else
     @products = Product.order("created_at DESC")
  end
end

product.rb

def self.search(search)
   where("title LIKE ? OR description LIKE ?","%#{search.strip}%","%#{search.strip}%")
  end
end

1 个答案:

答案 0 :(得分:1)

如果我没错,您将在产品模块的index.html.erb中显示成功的搜索结果。您将搜索结果传递到@products对象。因此,在您的index.html.erb文件中,您可以显示未找到结果等消息,

  <% if (@products) %>
    <% if (@products.empty?) %>
      <p>No product found.</p>
    <% else %>
      <% @products.each do |product| %>  
        <p><%= link_to "#{product.name}", product %></p>
      <% end %>
    <% end %>
 <% else %>
   <p>Use the search form to search for product.</p>
 <% end %>