2016-06-24 74 views
0

我一直在为这个搜索表单寻找我正在构建的用于学习Rails的应用程序。搜索与所有产品一样显示搜索结果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 %> 

在我的意见/产品/ 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 

回答

0

,而不是使用

@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}%" 
+0

感谢答案, 当我更改代码轨道给我这个错误'绑定变量的错误数量(1为2):名称像?或描述如''在这行'def self.search(query) where(“name like?or description like?”,“%#{query}%”) end' – DaudiHell

+0

语法错误,而不是两个你正在使用一个单一的变量我已经更新了答案。 –

+0

谢谢,它现在有效,但它仍然给我的所有产品的清单,而不是我所搜索的, – DaudiHell