Building an ActiveRecord condition parameter can result in a lot of unattractive code if it needs to depend on various things. E.g. if you need to find records that match multiple criteria given by the user, you might end up writing a lot of code to do so.
Using a hash as a condition might work in some cases:
1 conditions = {} 2 conditions[:orderno] = orderno unless orderno.blank? 3 conditions[:color] = color unless color.blank? 4 ... 5 Product.find(:all, :conditions => conditions)
However this only works for simple searches (where values are matched by equality). If you try to build a slightly more complex condition (like searching for a substring in the name of a product, or for products that are cheaper than a given price), a hash won’t work and you need to use an array for the condition. This usually leads to clumsy code that needs to assemble the query string and its parameters in the right order depending on the given criteria. However, by extending the Array class with a helper method, everything becomes easier and nicer:
Read more »