Here’s an odd one for you, and I leave it up to you to decide whether it is a bug or a feature.
A great little shortcut to be able to do in find methods on your models is for when you know a field is null you can just do e.g.:
Product.find_all_by_category_id_and_description(42, nil)
This will return a list of all products in category 42 with no description, as you can see from the debug output:
SELECT * FROM `products` WHERE (`products`.`category_id` = 42 AND `products`.`description` IS NULL)
Great, nice and simple.
So what if you want to find all products in category 42 that have a description? Normal logic might suggest something like this:
Product.find_all_by_category_id_and_description(42, !nil)
That logic works in Ruby itself, but Rails does something funny when it comes to piping that into a query:
SELECT * FROM `products` WHERE (`products`.`category_id` = 42 AND `products`.`description` = 1)
Huh? Well that doesn’t work. Given that Rails is smart enough to recognize that the “nil†passed in should get converted to “IS NULL†in the query, it’s disappointing that it doesn’t do likewise for “!nilâ€Â.
Other Posts That Might Interest You




