Almost every application does need search feature. Even if not direct feature You need some efficient way to narrow data selection. And I do like to have clean and compact code :) so I have spent some time to create my own search schema which I’d like to share with You.
First – what I’m talking about? Let’s assume You need to create some kind of report and has to provide several options to narrow down scope of entries. Since Active Record requires You to create part of SQL query in :conditions it is easy to create some not nice looking code with string joining, wondering if You should add AND operator and so on.
In most cases You don’t need full blown search capabilities (like with Ferret) and You want to keep Your dependencies list as short as possible.
How to search?

I came up with following code:
conditions = ["1=1"]
cond_data = []
includes = [:association_used_for_display]
unless params[:condition_1].blank?
conditions << "field_1 = ?"
cond_data << params[:condition_1]
end
unless params[:condition_2].blank?
conditions << "other_table.field_2 = ?"
cond_data << params[:condition_2]
includes << :some_association #for other_table
end
unless params[:condition_3].blank?
conditions << "one_more_table.field_3 like ?"
cond_data << "#{params[:field_3]}%"
includes << :one_more_association #to get one_more_table
end
@results = Model.find(
:all,
:conditions => [ conditions.join(" and "), *cond_data ],
:include => includes)
The idea is to keep array conditions with entries to create :conditions option and cond_data array to keep arguments to substitute all question marks.
With includes we can add associations we need to load when criteria need it. We can preset some associations to force load some data always needed for view creation (association_used_for_display in this example).
Using this schema allows easilly add new criteria – it just another unless statement.
So what do You think about it?
I’m curious what do You think about this approach – or You do have some own solutions? I’m waiting for Your comments!
Leave a Reply