我想实现类似的东西,即用 SQL 通配符替换客户输入中的空格%
,以便搜索字段“Foo Bar”匹配“Foo Bar”,还匹配“Foomster Q. Bar”和“Foo Glolubar” . 我还想将通配符添加到实际搜索参数的开头和结尾,以便“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
和标记由
Twitter 的 Bootstrap 框架提供):span8
btn btn-large btn-primary
<% 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
. 这些指的是我在 file 中定义的自定义搜索谓词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
被加载。)