2013-08-29 68 views
0

我做了一個搜索(過濾)表單來根據給定的值過濾我的對象。有一個公司模型和搜索將根據其屬性。這是我的index.html.erb:rails 3部分搜索

<% 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 

這是我的模型company.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家公司命名卡拉哈里,卡拉哈里2和卡拉哈里2。當我搜查卡拉哈里時,它只發現了一家公司,卡拉哈里。我的意思是在卡拉哈里2或卡拉哈里2找不到卡拉哈里。只有找到完全匹配。當我搜索卡拉時,它什麼都沒找到。我怎樣才能最簡單地解決這個問題?我是新來的鐵軌,不想搞亂很多東西。

回答

2

最簡單的變化,將讓你想要的是增加一個通配符搜索查詢的末尾:與LIKE使用時

q = "%#{search}%" 

%匹配任何東西,所以你作爲目前編寫的代碼將匹配任何東西結尾與您的輸入(所以它會匹配'foo'到'afoo','b_foo'和'1 3 5 x foo')的查詢,但沒有匹配的通配符,它​​不會匹配包含的內容查詢但不包含結束與它(所以'foo'將不匹配'f oobar'或'afoox')。

+0

非常感謝 – kalahari