开发者

Writing a search method that matches loosely

I have just watched the railscast about a simple search form and I want to do something like that in my a开发者_JAVA技巧pp, but I don't want to find just results that match exactly.

I have a model named Project with the following fields:

  • name,
  • description,
  • keyword1, and
  • keyword2.

Given the code taken from the railscast:

models/project.rb

def self.search(search)
    if search
        find( :all, :conditions => ['name LIKE ?', "%#{search}%"] )
    else
        find(:all)
    end
end

If I want to search for "Pizza", and I would want it to match a project named "Master Pizza Project" with keyword1 => "MasterPizza" and keyword2 => "Pizza", how would I refactor the above code?

Also, is case sensitivity a problem?


There is another railscast where Ryan Bates talks about utilizing Sphinx to make full text search. I would highly recommend such an approach instead of doing things from scratch :

http://railscasts.com/episodes/120-thinking-sphinx


You'd need to split the query into atoms, run each atom as a separate query then merge the results from each atom.

At this point things are getting pretty complex, you'd be better off using a search library such as Acts as Indexed which takes care of all this for you.

[Disclosure] I'm the author of Acts as Indexed.


Check out the Metasearch and Metawhere gems.


I don't quite understand your q but I hope this makes sense:

def self.search(search)
    if search
     where('title LIKE ? OR keyword1 LIKE ? OR keyword2 LIKE ?',"%#{search}%", "%#{search}%","%#{search}%")
    # find(:all, :conditions => ['title LIKE ?', "%#{search}%"])
    else
      all
    end
  end    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜