Search Examples

Searching for a phrase in a record column

The find method can use conditions supported by most databases (including SQLite). The following code will find all movies that have mockingbird in the title:

   phrase = 'mockingbird'
   search_pattern = '%' + phrase + '%'
   @movies = Movie.find(:all,
      :conditions => ["title like ?", search_pattern])

Note that the percent sign is a wild card character that can match any number of characters. By putting the percent sign before and after the phrase, the phrase can appear anywhere in the title. Also note how the search_pattern is substituted in place of the question mark to create the search condition.

Ordering records

Another option for the find method allows you to specify the order in which the record objects appear. This example orders the movies by their year.

    @movies = Movie.find(:all, :order => "year")

By default, the objects are placed in ascending order, but if you want them to appear in descending order (most recent movies first), you can add the DESC option:

    @movies = Movie.find(:all, :order => "year DESC")

Combined parameter-based example

This example puts it all together and assumes that a form has the phrase and order parameters specified:

    phrase = params[:phrase]
    order = params[:order]
    search_pattern = '%' + phrase + '%'
    @movies = Movie.find(:all,
      :conditions => ["title like ?", search_pattern], :order => order)