I’m looking for a way to do a complex search across a variable set of multiple fields in a Rails form. In .NET, I’d just build up dynamic SQL by brute force, but that doesn’t seem very Rails-ish, so I went hunting.
- Use find_by_sql and the join method to build up a condition string. This is essentially the brute force method translated to Rails.
- Acts_as_Ferret lets you set up full-text searching across multiple fields, but that doesn’t actually fit the requirements.
- ModelSearch is a plugin that was demoed in one of the talks at RailsConf Europe 2006. It lets you do things like
search = ProductSearch.new
search.keyword = 'television'
search.max_price = 300
search.sort = :price
search.find(:all)
This is cool, but it doesn’t seem to have actually been released into the wild yet.
articles = Article.find_where(:all) do |article|
article.title =~ 'Lorem%'
article.author.name 'Ezra'
article.comments.user.name ‘Fab’
end
- Squirrel is another plugin inspired by ez-where. It has a similar syntax and includes pagination support.
Right at the moment I’m inclining towards using Squirrel to meet my requirements.