I’ve been playing around with some easier ways of specifying
conditions in active record, and have come up with a little plugin
that some may find useful. Currently active record finder and
calculations methods can take a :conditions option with a string or
array listing some sql conditions, eg:
Animals.find :first, :conditions => “name = ‘Tiger’”
My plugin enables simple conditions like this to be written without
any SQL at all, using a hash instead of an array or string:
Animals.find :first, :conditions => {:name => ‘Tiger’}
As well as simple equality conditions, other tests such as more than,
less than and contains can also be specified:
Animals.find :first, :conditions => {:name_starts_with => ‘Tig’}
Animals.find :all, :conditions => {:population_more_than => 1_000_000}
Conditions can be combined:
endangered_tigers = Animals.find :all, :conditions => {:name_contains
=> ‘Tiger’, :population_less_than => 10_000}
These conditions can also be used in calculations and scoped queries:
Animals.count :conditions => {:population_more_than => 1_000_000}
Animals.with_scope :find => {:conditions => {:name_contains => ‘Tiger’}}
do
Animals.find :all
end
Finally, here’s an simple way to use this plugin to add lots of data
slicing and dicing to any list actions you might have:
class AnimalController < ActiveController
def list
animal_conditions = params.dup.reject! {|k, v| [:action, :control
ler].include? k}
@animals = Animal.find :all, :conditions => animal_conditions
end
end
This allows urls such as
/animal/list?name_starts_with=T&population_less_than=1000
Please take a look, the code is available at
svn://rubyforge.org/var/svn/popdog/slice_and_dice/tags/REL-0.1
I’d welcome any comments or ideas on how to improve this (currently
very simple) plugin. I do have some planned extra features of my own,
so watch this space!
Tom