Ransack搜索,如何通过分割输入搜索参数来搜索每个词 [英] Ransack search, how to search for each word by splitting input search parameter
问题描述
我目前正在试验使用 ransack gem
在 Rails 中对模型进行搜索.就目前而言,我使用的是基本设置.
I am currently experimenting using the ransack gem
to conduct a search on a model in Rails. As it stands I am using the basic setup.
控制器:
def index
@q = Person.search(params[:q])
@people = @q.result(:distinct => true)
end
查看:
<%= search_form_for @q do |f| %>
<%= f.label :name_cont %>
<%= f.text_field :name_cont %>
<%= f.submit %>
<% end %>
我设法找到了很多关于在多个字段上进行搜索的信息,但是,我没有找到任何可以帮助我拆分 :q
参数的信息,从而使我能够在以 search for ??? 的形式输入的搜索字符串中搜索每个(未知数量的)单词和 ???和 ???...
,而不是在一个部分中搜索整个字符串
I have managed to find lot of information about conducting searches on multiple fields, however, I haven't managed to find anything to help me to split up the :q
parameter and thereby enable me to search for each of the (unknown quantity of) words in the search string entered in the form of search for ??? AND ??? AND ??? ...
, rather than searching for the entire string in one section
有人能指出我正确的方向吗?
Is anybody able to point me in the right direction?
推荐答案
在花了大量时间研究这个问题却没有结果后,我选择了一个非常有效的自定义非洗劫选项.
Having spent a chunk of time looking into this with no results, I opted for a custom, non-ransack option which works perfectly well.
在View.html.erb
<%= form_tag siteindex_search_allproducts_path, :method => 'get' do %>
<b>Search: </b> <%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
<% end %>
在Controller
@findproducts = Allproduct.order('price ASC').search(params[:search])
在model.rb
def self.search(*args)
return [] if args.blank?
cond_text, cond_values = [], []
args.each do |str|
next if str.blank?
cond_text << "( %s )" % str.split.map{|w| "product_name LIKE ? "}.join(" AND ")
cond_values.concat(str.split.map{|w| "%#{w}%"})
end
all :conditions => [cond_text.join(" AND "), *cond_values]
end
这篇关于Ransack搜索,如何通过分割输入搜索参数来搜索每个词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!