December 22, 2006
CriteriaQuery - Cuter ActiveRecord Finders
Post by Peter Cooper
CriteriaQuery is a plug-in for Ruby on Rails that extends ActiveRecord with a shedload of useful and logical methods so that you can chain together complex queries in an object-oriented manner. I discovered it thanks to this article by Jonathan Conway.
CriteriaQuery makes it possible to make queries like this:
Compare that to the alternative:
Person.find(:all, :conditions=>['people.name LIKE ? AND addresses.city LIKE ?', 'Fred Bloggs', 'London'], :include=>[:city])
There have been several alternatives at improving the syntax for finding things with ActiveRecord. Consider ez_where which would work in such a way:
Person.find_where(:all, :include => :city) do |person, city| person.name =~ "%Fred Bloggs%" city.name =~ "%London%" end
I haven't made my own mind up about what I prefer, although each technique has its pros and cons. The point of this day on the advent calendar is to show that, no, you don't have to do it the default way. There are options, and good ones.