More Advanced Searching Techniques with Rails

{ Posted on Mar 06 2009 by Dan }

For my first real post, I want to start off looking at searching and drilling down a list of objects. It’s based on Railscast 112, the one on anonymous scopes, but with a few other things thrown in for good measure. For the purposes of this example, I’m going to use these classes

# models/employee.rb
class Employee < ActiveRecord::Base
  belongs_to :employer
  validates_presence_of :employer_id, :first_name, :last_name, :start_date, :salary
# models/employer.rb
class Employer < ActiveRecord::Base
  belongs_to :region
  has_many :employees
  validates_presence_of :name
  validates_uniqueness_of :name
# models/region.rb
class Region < ActiveRecord::Base
  has_many :employers
  validates_presence_of :name
  validates_uniqueness_of :name

One thing that always seems to be a problem for me, is working with dates in rails. So, instead of using the classic rails date_select, I am going to use Filament Groups jQuery UI Date Range Picker.

To begin, I generated the scaffold for the three models

./script/generate scaffold region name:string
./script/generate scaffold employer name:string region_id:integer
./script/generate scaffold employee employer_id:integer first_name:string last_name:string start_date:date salary:integer

I made a few changes to the views to include select lists where appropriate, but thats not so important at the moment. Take a look at the download if you would like to see those view changes.

The main stuff happens in the employees_controller. I wanted to keep this fairly simple, so there is no separate search action. It works out better this way anyway. Here is what the employees index action looks like

def index
  @search = params[:search].blank? ? {} : params[:search]
  @employees = @scope.find(:all, :order => ', last_name', :include => :employer)
  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @employees }

As you can see, @search will be a blank hash if there is not an incoming search parameter.

Both the get_dates and collect_employees methods, are protected methods in the employees controller. The method get_dates, takes the single input field of the calendar select, and splits up the dates so employees start_dates can be filtered through any range of dates. It looks like this…

def get_dates
  unless @search.blank?
    dates = @search[:start].split('-')
    dates.each_with_index do |d, i|
      @search["date_#{i}".to_sym] = Date.parse(d.strip) unless d.blank?

The get_dates method extracts the two dates from @search[:start] and creates two new attributes, date_0 and date_1. This also keeps the :start attribute intact, and allows it to be redisplayed in the view. Also, if the start field only includes 1 date, the query will find all employees that started on that date till now.

The next method should look familiar if you watched railscast 112 . Here it is…

def collect_employees
  @scope = Employee.scoped({})
  @scope = @scope.scoped :conditions => ['first_name like ?', "%#{@search[:first_name]}%"] unless @search[:first_name].blank?
  @scope = @scope.scoped :conditions => ['last_name like ?', "%#{@search[:last_name]}%"] unless @search[:last_name].blank?
  @scope = @scope.scoped :conditions => { :employer_id => @search[:employer_id] } unless @search[:employer_id].blank?
  @scope = @scope.scoped :conditions => { :employers => { :region_id => @search[:region_id] } } unless @search[:region_id].blank?
  @scope = @scope.scoped :conditions => ['salary >= ?', @search[:salary_min] ] unless @search[:salary_min].blank?
  @scope = @scope.scoped :conditions => ['salary <= ?', @search[:salary_max] ] unless @search[:salary_max].blank?
  @scope = @scope.scoped :conditions => ['start_date >= ?', @search[:date_0] ] unless @search[:date_0].blank?
  @scope = @scope.scoped :conditions => ['start_date <= ?', @search[:date_1] ] unless @search[:date_1].blank?

As you can see, there is more going on than just refining the results by attributes of the employee. You can also find employees by their employer and even employees by the region their employer is located in.

I wanted to use a search model, like in railscast 111, so I could use f.text_field throughout the form, but I didn’t want to create a database object, and my attempts to finesse the code to work in that way proved fruitless. So, for the view, I used the generic form_for and text_field_tag’s like this…

<% form_for :search, :url => { :controller => 'employees', :action => 'index' } do %>
    <label for="search_first_name">First Name:</label><br />
    <%= text_field_tag 'search[first_name]', @search[:first_name], :id => 'search_first_name' %>
    <label for="search_last_name">Last Name:</label><br />
    <%= text_field_tag 'search[last_name]', @search[:last_name], :id => 'search_last_name' %>
    <label for="search_employer_name">Employer:</label><br />
    <%= select_tag 'search[employer_id]', employee_select_helper('Employer'), :id => 'search_employer_name' %>
    <label for="search_region_name">Region:</label><br />
    <%= select_tag 'search[region_id]', employee_select_helper('Region'), :id => 'search_region_name' %>
    <label>Salary</label><br />
    <%= text_field_tag 'search[salary_min]', @search[:salary_min], :id => 'search_salary_min' %> -
    <%= text_field_tag 'search[salary_max]', @search[:salary_max], :id => 'search_salary_max' %>
  <div id="date_search">
    <label for="search_start">Start Date</label><br />
    <%= text_field_tag 'search[start]', @search[:start], :id => 'search_start' %>
  <%= submit_tag "search" %>
<% end %>

The employee_select_helper is in the employeesHelper and thanks to some ruby magic, it looks like…

def employee_select_helper(object)
    '<option></option>' + options_from_collection_for_select(object.constantize.find(:all, :order => 'name'), 'id', 'name', @search[object.foreign_key.to_s].to_i)

I ran into a couple of issues with the daterangepicker plugin displaying the dropdown correctly. The daterangepicker, by default, appends the slick looking calendar picker to the html document body, but this creates a problem whenever there is data after the daterangepicker, causing it to append to the bottom of the page and not work as expected. To fix that, I edited the daterangepicker.jQuery.js (around line 269) like this…

// from
// to

And application.js is simple as this…


As for the daterangepicker plugin, I placed all the js files in the javascripts directory and all the css files inside the stylesheets directory. The plugin also includes an images directory, and in order to avoid having to edit all the image urls inside the css, I just placed the images directory inside the stylesheets directory. Maybe not a best practice, but it makes things easier at this point.

Now, you can search for employees in any combination of employer, employers region, a start date range, salary range, or first and last name. This concludes my further exploration of anonymous scopes and the Filament Group jQuery UI Date Range Picker. Hopefully you found something of value. The included app uses sqlite3 and also has a little sample data with it. You should only need to download, unzip and run script/server to see the basic, no style applied employee search app. As always, comments, suggestions and improvements are welcome.

Download: searching

Post a Comment

Powered by WP Hashcash