The Pug Automatic

Make blank acts_as_solr queries find all records

Written September 3, 2007. Tagged Ruby, Ruby on Rails.

I wrote a small piece of code that makes acts_as_solr's various querying methods find all entries (subject to facet options etc) instead of no entries when the query is blank.

This is useful if acts_as_solr powers a filtering interface: all entries should be returned if no query has been specified, and facets and queries can be used to view subsets.

Stick empty_query_finds_all.rb in /lib and require "empty_query_finds_all" in config/environment.rb.

The code is simply this:

# Modifies the innards of acts_as_solr so empty queries find every model instance
# instead of none, e.g. User.count_by_solr('') and Group.find_by_solr(nil).

module ActsAsSolr
module FindAllExtension
FIND_ALL_QUERY = 'type:[* TO *]'

def self.included(mod)
mod.alias_method_chain :parse_query, :find_all

def parse_query_with_find_all(query=nil, *args)
query = query.blank? ? FIND_ALL_QUERY : query
parse_query_without_find_all(query, *args)


module ActsAsSolr::ParserMethods
include ActsAsSolr::FindAllExtension

Note that this makes use of alias_method_chain which is edge Rails. You can use multiple alias_methods instead.