Topic: HOWTO: Adding search to your rails application
Sticky:: Please read the post below. I think you will find the next method even simpler.
This is a short guide on adding search to your Rails models.
For this tutorial, I'm using a model called Product and product has the following attributes: name, description, price. If you're new to rails, what this means is that you have a database table called products, and this table has the columns name, description and price (including id of course).
Now, the first thing to do is to install the ferret gem. Without this, this tutorial is moot. Open a command prompt and type:
gem install ferret
Next, you will need to download the simple_search plugin for rails. The svn repositry is located at:
So you can get it through Subversion using the command
If you don't have Subversion you can download it from http://subversion.tigris.org/project_packages.html. After you download simple_search, place it in the vendor/plugins directory of your rails application.
Now go to app/models and open product.rb (i.e the file for your Product model or whichever model you are using). Your model should look something like this:
class Product < ActiveRecord::Base
indexes_columns :title, :description, :into=>'idx'
self.idx = self.index_repr
Now there is a bit of explaining to do here. In addition to all the other columns Product has, you should also add another one called idx which has the type "TEXT" in your SQL database. This means that the columns for product should be id, name, description, price and idx (which is a TEXT column). idx contains the searchable terms for your product. You will notice the line at the top which reads "indexes_columns :title, :description, :into => 'idx' ". Well simple_search simply takes the value of these columns and creates a searchable index which it puts into the idx column. I could well have said "indexes_columns :title, :description, :price :into => 'idx' " which will also include the price as part of our index.
I've added some filters to the product model. Before a product is saved or updated, the idx value is first determined using the 'make_index' method. This saves you the trouble of doing this in your controller each time you save or update your product.
And that is pretty much it. You can fire up script/console with "ruby script/console" for your application.
Create a new product with
Product.create(:name => 'ninja_turtle', :description => 'It barks and eats your mother', :price => 20)
Then you can now type Product.find_using_term("ninja") and your recently created product should turn up. Use find_using_term to return any products that match your given term.
Last edited by daibatzu (2006-09-20 05:10:48)