views:

299

answers:

5

I am trying to figure out how to add search to my rails application. I am brand new so go slow. I have created a blog and done quite a bit of customizing including adding some AJAX, pretty proud of myself so far. I am having trouble finding any good tutorials about how to add this functionality. Basically I just want to enable a full search to search my posts table. What is the easiest way to do this?

+3  A: 

Depending on the RDBMS you are using there might be a built-in solution for fulltext search.

Otherwise you might check out Sunspot (and the Rails plugin) which uses Apache Solr for fulltext search and is easy to use. Especially writing queries/searches is much more fun than with the standard acts_as_solr plugin.

Edit Oh, and here is a screencast on Sunspot for the visual people.

Marcel J.
I tried Sphinx, Ferret and Solr and I must say Sunspot + Solr is the best match.
Simone Carletti
+2  A: 

I'd suggest using the acts_as_solr plugin. I'm just starting with Rails too and that's the search indexing plugin recommended by my professor. It includes the SOLR search engine in the plugin. The site includes installation and usage instructions.

Basically, as the usage shows, you would just include the acts_as_solr tag in whichever models you want to be searchable, and then specify which attributes in your model you want to be indexed for searching on... so you'd do something like:

class Post < ActiveRecord::Base
    acts_as_solr :fields => [:post, :comments, :whatever]

And for searching you'd do something like...

    Post.find_by_solr(query_string)
kchau
A: 

Ferret can do that.

JRL
A: 

The easiest way to do this would be to do something like this:

results = Post.find(:all, :conditions => "post_body LIKE '%#{search_string}%'" )

However, this is pretty limited in that it will only search for the exact word or phrase you are looking for (not to mention a vulnerability to SQL injection). As I mentioned, this is the "easiest" way to do a search, but definitely not the best. I would look into using acts_as_solr if you want to do this seriously.

robotshapes
If you want to keep it as simple as that, at least try it with :conditions => ["post_body LIKE '%?%'", search_string] which at least protects you from SQL injection vulnerabilities :-)
webmat
+3  A: 

There's a great Railscast on Thinking Sphinx, which is my favorite above the other mentioned options. It's fast, simple, and is continually being developed.

There's also SearchLogic which is great if you don't really need full text indexing (you probably don't for a blog). And a Railscast to go along with that as well.

bensie