I have a Transaction model in a Rails 3.1.0.rc4 app with a decimal attribute amount. I have records where the amount attribute is more than 0 as well as records where the amount attribute is less than 0. I want to get all the records where the amount is more than 0. I tried Transaction.where('amount > 0') and Transaction.where('amount > 0.0') but in both cases, all the records are returned, including the ones with a negative amount. When I run Transaction.where('amount < 0') or Transaction.where('amount < 0.0') no records are returned.
Is it possible to do these types of queries on decimal attributes?
The problem is with SQLite and your migrations – if you open up your SQLite database and run
SELECT typeof(amount) FROM transactions LIMIT 1you’ll see that Rails is creating your decimal field as a BLOB type instead of the decimal REAL type.I’m not sure if this is a Rails bug or not, but for the time being you can get around it by casting the amount in your where clause:
You can also get around this by using straight SQL in your migration with the
executemethod to createamountas a REAL field to begin with (see http://api.rubyonrails.org/classes/ActiveRecord/Migration.html).