Search code examples
ruby-on-railsruby-on-rails-3searchransack

Ransack search, how to search for each word by splitting input search parameter


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.

Controller:

def index
  @q = Person.search(params[:q])
  @people = @q.result(:distinct => true)
end

View:

<%= search_form_for @q do |f| %>
   <%= f.label :name_cont %>
   <%= f.text_field :name_cont %>
   <%= f.submit %>
<% end %>

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?


Solution

  • Having spent a chunk of time looking into this with no results, I opted for a custom, non-ransack option which works perfectly well.

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

    In Controller

    @findproducts = Allproduct.order('price ASC').search(params[:search])
    

    In 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