rails 3部分搜索

时间:2013-08-29 15:03:46

标签: ruby-on-rails-3 search

我制作了一个搜索(过滤)表单,根据给定的值过滤我的对象。有一个公司模型,搜索将根据其属性。这是我的index.html.erb:

<% provide(:title, 'All companies') %>
<h1>All companies</h1>

<%= form_tag companies_path, :method => 'get' do %>
  <%= hidden_field_tag :direction, params[:direction] %>
  <%= hidden_field_tag :sort, params[:sort] %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>

<table class="pretty" border="1" cellpadding="10">  
  <tr>  
    <th><%= sortable "name" %></th>
    <th><%= sortable "city" %></th>
    <th><%= sortable "country" %></th>
    <th><%= sortable "street_address" %></th>
    <th><%= sortable "sector" %></th>
    <th><%= sortable "telephone" %></th>
    <th><%= sortable "fax" %></th>
    <th>DELETE</th>
  </tr>  

  <% for company in @companies %>  
  <tr class="<%= cycle('oddrow', 'evenrow') -%>">  
    <td><%= link_to company.name, company %></td>
    <td><%= company.city %></td>
    <td><%= company.country %></td>
    <td><%= company.street_address %></td>
    <td><%= company.sector %></td>
    <td><%= company.telephone %></td>
    <td><%= company.fax %></td>
    <td><% if current_user.admin?  %>
          || <%= link_to "delete", company, method: :delete,
                              data: { confirm: "You sure?" } %>
        <% end %></td>
  </tr>
  <% end %>
</table>
<%= will_paginate @companies %>

这是我的companies_controller.rb

helper_method :sort_column, :sort_direction
def index
    @companies = Company.search(params[:search]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 10, :page => params[:page])
end

这是我的模特公司.rb

class Company < ActiveRecord::Base
  attr_accessible :city, :country, :fax, :name, :reseller, :sector, :street_address, :telephone, :id
  has_many :users , dependent: :destroy

  def name_for_form
    "#{name}"
  end

  def self.search(search)
    if search
      q = "%#{search}"
      where('name LIKE ? OR city LIKE ? OR country LIKE ? OR street_address LIKE ? OR telephone LIKE ? OR fax LIKE ? OR sector LIKE ?',
            q,q,q,q,q,q,q)
    else
      scoped
    end
  end

  validates :city, presence: true
  validates :country, presence: true
  validates :fax, presence: true
  validates :name, presence: true
  validates :sector, presence: true
  validates :street_address, presence: true
  validates :telephone, presence: true
end

假设我有3家公司名为kalahari,kalahari 2和kalahari2。当我搜索卡拉哈里时,它只发现了一家公司,卡拉哈里。我的意思是它在卡拉哈里2或卡拉哈里2中找不到卡拉哈里。只找到完全匹配。当我搜索卡拉时,它什么也没找到。我怎样才能最简单地解决这个问题?我是铁杆新手,不想弄乱很多东西。

1 个答案:

答案 0 :(得分:2)

最简单的更改将获得您想要的内容,即在搜索查询的末尾添加通配符:

q = "%#{search}%"

%LIKE一起使用时匹配任何内容,因此您当前编写的代码将与结束的任何内容匹配您的输入(因此它将与&的查询匹配) #39; foo&#39; afoo&#39;,&#39; b_foo&#39;和&#39; 1 3 5 x foo&#39;),但最后没有匹配的通配符,它不会与包含查询的内容相匹配但不会与结束(因此&#39; foo&#39;将无法匹配&#39; foobar& #39;或&#39; afoox&#39;)。