【问题标题】:Search displaying search results as all products Rails App搜索将搜索结果显示为所有产品 Rails App
【发布时间】:2016-06-24 12:20:02
【问题描述】:

我一直在为我正在构建的用于学习 Rails 的应用编写此搜索表单。

它应该搜索产品,但是当我在搜索字段中输入一些产品名称时,它会给我一个所有产品的列表。解决方案可能很简单,但我还没有弄清楚,我很沮丧。

我尝试将@products 更改为其他名称,但没有成功。

有人可以检查一下并给我建议吗?

提前致谢 D

在我的 _navbar 中代码是

<%= form_tag search_products_path, class: 'navbar-form navbar-right' do %>
  <%= search_field_tag class: 'form-control', :id => 'searchbar',  :placeholder =>'Search', :name => "query" %>
  <%= submit_tag "Submit", class: 'btn btn-default', :name => nil %>
<% end %>

在我的观点/products/search.html.erb

<table class="table table-hover">
   <thead>
     <tr>
      <th>Name</th>
      <th>Description</th>
      <th>Designer</th>
      <th>Price</th>
      <th>Stock</th>
      <th>Image</th>

    </tr>
  </thead>

 <tbody>
  <% @products.each do |product| %>

  <tr>
    <td><%= link_to product.name, product %></td>
    <td><%= product.description %></td>
    <td><%= product.designer.designer_name %></td>

    <td><%= number_to_currency product.price %></td>
    <td><%= product.stock_quantity %></td>

    <td><%= image_tag product.image.thumb %></td>


 <% end %>
</tr>
</tbody>

在我的 product.rb 模型中我有这个代码

 class Product < ActiveRecord::Base


     mount_uploader :image, ImageUploader

     validates_presence_of :name, :price, :stock_quantity
     validates_numericality_of :price, :stock_quantity

     belongs_to :designer
     belongs_to :category
     belongs_to :page

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


  end

在 products_controller.rb 我有这个代码

 def search
    @products = Product.search(params[:query])
    @categories = Category.joins(:products).where(:products => {:id => @products.map{|x| x.id }}).distinct

 end

【问题讨论】:

    标签: ruby-on-rails ruby search


    【解决方案1】:

    而不是使用

     @q = "%#{params[:query]}%"
     @products = Product.where("name ILIKE ? or description ILIKE ?", @q, @q)
    

    使用

     @products = Product.search(params[:query])
    

    在模型中将代码更改为

    "name LIKE ? OR description LIKE ?", "%#{query}%", "%#{query}%"
    

    【讨论】:

    • 感谢您的回答,当我更改代码时,rails 给我这个错误wrong number of bind variables (1 for 2) in: name like ? or description like ? 在这一行def self.search(query) where("name like ? or description like ?", "%#{query}%") end
    • 语法错误,因为您使用的是单个变量而不是两个变量,我已经更新了答案。
    • 谢谢,它现在可以工作了,但它仍然给了我所有产品的列表,而不仅仅是我搜索的产品,
    • 尝试调试你的代码,你会在 "%#{query}%" 中找到什么
    • 好的,我对调试不是很有经验,但是当它给我[1] pry(Product)&gt; query =&gt; nil
    猜你喜欢
    • 2015-02-12
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 2016-04-07
    • 1970-01-01
    相关资源
    最近更新 更多