I’m trying to add a conditional where only records that meet the condition are grabbed from the Model. For example, I’m trying to only grab records from the Transaction model where the :price is either greater than or not equal to 0 (I’ve tried > and != but neither worked in the example below).
price = Transaction.where(:company_id => company).where(:price != 0.00)
I’ve also tried this:
price = Transaction.where(:company_id => company).where(:price != 0.00).collect{|item| if item.price.to_f > 0.00 {item.price.to_f} end}
…as well as other variations of the two above that did not work.
The first example above doesn’t produce an error but simply does not work. The condition is ignored. The second example produces a syntax error.
I’m also pretty sure there’s a way to do this using conditionals in SQL but don’t have any idea how to go about that.
Any suggestions?
This:
is the same as saying:
as a Symbol will never be equal to a Float;
where(true)is pointless as it just adds your databases’s true literal ('t'for PostgreSQL,1in SQLite and MySQL) to the WHERE clause and that doesn’t do anything useful; for example, if you say:then your SQL will end up like this in PostgreSQL:
and that’s the same as just saying
When a query is confusing you sometimes it is helpful to add a
.to_sqlat the end in the Rails console and see what the SQL ends up doing (and if you don’t know SQL then you should learn it if you intend to use a relational database in any capacity).You want to send the comparison to the database, not do it inside Ruby:
I’m assuming that your
pricecolumn is a decimal type rather than a floating point type; if I’m wrong then change it to decimal right now.