0

I have simple search (I want to keep that way) where I can make search Product name. But I want to add other column(Still Product model) intro_text.

Code so far:

Product.rb

def self.search(search)  
  if search  
   where('intro_text LIKE ? ', "%#{search}%")
  else     
   where('name LIKE ? ', "%#{search}%")    
 end  
end 

Search controller

@products_search = Product.search(params[:search]).paginate(:per_page => 5, :page => params[:page])

At this point when search occurs results are displayed just from intro_text field. Demo: Searching for phrase "Pez" should find all products that consists of this phrase and also all products that intro text consists of this phrase.

Also tried to :

 def self.search(search)  
     if search  
        where('intro_text LIKE ? ', "%#{search}%") || where('name LIKE ? ', "%#{search}%")
     else  
     end  
 end

But the result was the same! Can somebody give me some tip? I don't need any search gems.

Edgars
  • 913
  • 1
  • 19
  • 53

1 Answers1

1

If params[:search] has no value, then the else clause becomes:

where('name LIKE "%%"')

which isn't very helpful.

In the second example you posted, the first where() will return an ActiveRecord::Relation, and will always be trueish, so the || will never get triggered.

Also, using the same name for a local variable as the method is a little confusing.

Looks to me like you want a combined OR search?

def self.search(search_term)
  if search_term.present?
    where('intro_text LIKE ? OR name LIKE ?', "%#{search_term}%", "%#{search_term}%")
  else
    none # new in Rails 4, or you can do where('1 = 0')
         # for a scope that will never return records, but can still
         # chain your pagination, etc onto
  end
end
Unixmonkey
  • 18,485
  • 7
  • 55
  • 78
  • Thanks worked just great. But at this point,it is possible to somehow highlight found phrases in search results ? Without any gem ? – Edgars Jun 04 '14 at 18:34
  • If you are looping over results before printing, then you could replace them inline with a `span` that you can apply styling to: `new_result = result.gsub(params[:search], "#{params[:search]}")` or use a JavaScript implementation like http://stackoverflow.com/questions/17521399/highlight-search-term-using-javascript-in-an-html – Unixmonkey Jun 04 '14 at 20:34