I am using Rails 3.2.2 and I would like to retrieve records from the database where at least 3 of 10 column values are present. That is, if I have a class (a MySQL database table) with 10 attributes (table columns) whose values can be nil (null), then I would like to perform a query so to return objects (records) where at least 3 of those 10 attribute values are present (not null).
Is it possible? If so, how to make that?
UPDATE If I have a class (a MySQL database table) with 10 attributes (table columns) whose values can be nil (null) or “” (not null), then I would like to perform a query so to return objects (records) where at least 3 of those 10 attribute values are present (not null and not ““).
You could compare against the sum of testing each individual column
IS NOT NULLAND<>:This works because the boolean result of each test is implicitly converted to either
1(if true) or0(if false); therefore the sum is the number of columns which are neitherNULLnor' '.Alternatively, you could handle the
NULLcase usingIFNULL():