我想實現類似的東西,那就是,通過SQL通配符%
替換 客戶輸入空格,以便搜索領域的「富酒吧」將 匹配「富酒吧」,也有「 Foomster Q. Bar「和」Foo Glolubar「。我還希望 將通配符添加到實際搜索參數的開頭和結尾,因此012ff即「Fiefoo Newton Barrister」也將是一個匹配項。
這裏是如何。的app/controllers/customers_controller.rb
的相關部分:
class CustomersController < ApplicationController
# GET /customers
# GET /customers.json
def index
@search = Customer.search(params[:q])
@customers = @search.result
...
respond_to do |format|
format.html # index.html.erb
format.json { render json: @customers }
end
end
...
end
app/views/customers/index.html.erb
(在 span4
,span8
和btn btn-large btn-primary
標記由 Twitter's Bootstrap framework提供)視圖的相關部分:
<% require 'action_view' %>
<div class="row">
...
<div class="span4"> <!-- The search criteria -->
...
<%= search_form_for @search do |f| %> <!-- this is a Ransack-provided form -->
<div class="field">
<%= f.label :customer_name_whitespaces_match_anything, "Name is or contains:" %>
<%= f.text_field :customer_name_whitespaces_match_anything, class: "my-textbox" %>
...
<%= f.label :customer_address_whitespaces_match_anything, "Address is or contains:" %>
<%= f.text_field :customer_address_whitespaces_match_anything, class: "my-textbox" %>
...
</div>
<br/>
<div class="actions">
<%= f.submit "Search", class: "btn btn-large btn-primary" %>
</div>
<% end %>
</div>
<div class="span8"> <!-- The search results -->
...
<table border="1" cellpadding="5">
<tr>
<th><%= sort_link(@search, :customer_name, "Customer name") %></th>
...
<th><%= sort_link(@search, :customer_address, "Address") %></th>
...
</tr>
<% @customers.each do |c| %>
<tr>
<td><%= link_to c.customer_name, customer_path(c, search: @search) %></td>
...
<td><%= c.customer_address %></td>
...
</tr>
<% end %>
</table>
</div>
...
</div>
你會發現搜索謂詞customer_name_whitespaces_match_anything
和customer_address_whitespaces_match_anything
。這些是指我在文件config/initializers/ransack.rb
中定義的自定義 搜索謂詞。它 內容是:
Ransack.configure do |config|
config.add_predicate 'whitespaces_match_anything',
:arel_predicate => 'matches', # so we can use the SQL wildcard "%"
# Format the incoming value: replace spaces by the SQL wildcard "%".
:formatter => proc {|v| "%"+v.gsub(" ","%")+"%"}
end
現在擺在它給SQL 查詢,但搜索後,搜索表單的輸入域還是原來顯示 搜索的用戶輸入的搜索詞是由自定義謂詞被改寫的。
(在搜索結果中,我從客戶的名義單獨 客戶的鏈接,這將導致視圖app/views/customers/show.html.erb
是 加載。)