Easy filtering by optional criteria in Rails applications

Posted on December 11th, 2007 in Nerdy,ruby,ruby on rails by toholio

I’ve frequently needed a very simple search method that allows partial matches for any combination of fields in a table. The following snippet shows how an ActiveRecord derived object might have a filter to allow for selection of records given a set of partial values.

class YourClass < ActiveRecord::Base
   def self.filter( partial_values )
    # don't bother at all if there is no search object
    return find(:all) unless partial_values
 
    con_string = ""
    con_array = []
 
    # build collection of conditions
    partial_values.each do |key,value|
      if value != "" then
        con_string += " and " if con_array.size > 0
        con_string += "#{key} LIKE ?"
        con_array << "%#{value}%"
      end
    end
 
    # construct the actual conditions array
    conditions = [con_string]
    con_array.each { |item| conditions << item }
 
    find(:all, :conditions => conditions)
  end
end

To use this you would obtain a set of search parameters, one for each filterable column, and pass it to YourClass.filter as a hash to get the matching rows.

So if you had a table with title and category columns you might create a page containing a form to collect partial value for filtering. When creating the form, assuming you will use Rails’ form helpers, the fields_for :collection function is nice as it will allow for easy collection of a hash for the field values.

<% form_tag your_object_path, :method =>"get" do %>
	<% fields_for :partial_values do |f| %>
		Title contains: <%= f.text_field :title %><br />
		Category contains: <%= f.text_field :category %><br />
	<% end %>
	<%= submit_tag "Filter items", :name => nil %>
<% end %>

Then once the form is submitted you would get the appropriate results in your controller using:

@your_objects = YourClass.filter( params[:partial_values] )

Post a comment