2

I have a rails app and have decided to have a search. I have a search textfield and the controller takes care of everything. In my search method

def self.search(search)
    if search
      str = []
      search.split.each do |s|
        a = find(:all, :conditions => ['title or content LIKE ?', "%#{s}%" ])
        str = (str + a).uniq
      end

    else
      find(:all)
    end
  end

I want to be able to handle multiple word searches. If you remove the each...loop it works fine with 1 word searches. Anyways, I would like to find the related posts for each word that is searched and return a combination of that.

Ex. If someone searches "Greatest Player" it will return all instances of posts that have the title or content "Greatest" and any that have the title or content "Player"

Vasseurth
  • 6,354
  • 12
  • 53
  • 81

3 Answers3

6

You most likely should be looking at full text searching:

Community
  • 1
  • 1
Jeff Perrin
  • 8,094
  • 1
  • 23
  • 19
2

Shouldn't it be

a = find(:all, :conditions => ['title or content LIKE ?', "%#{s}%" ])
slowpoison
  • 586
  • 3
  • 20
2

All you needed was to change the find statement to Mischa's code and add a return statement

Working Code:

def self.search(search)
    if search
      str = []
      search.split.each do |s|
        a = where(title LIKE ? or content LIKE ?', "%#{s}%", "%#{s}%")
        str = (str + a).uniq
      end
    return str

    else
      find(:all)
    end
  end
Weston Ganger
  • 6,324
  • 4
  • 41
  • 39