As far as I know, it should be possible to do the following in Rails:
ActiveRecord::Base.connection.select_all("SELECT MONTH(created) AS month, YEAR(created) AS year FROM orders WHERE created>=$1 AND created<=$2 GROUP BY month ORDER BY month ASC",nil,[['created',1],['created',2]])
but sadly, this is not working at all. whatever format I try to use, the $1
and $2
are never replaced with the corresponding values from the bind array.
Is there anything more i should take care of?
You should use sanitize_sql_array
in your model, like this:
r = self.sanitize_sql_array(["SELECT MONTH(created) AS month, YEAR(created) AS year FROM orders WHERE created>=? AND created<=? GROUP BY month ORDER BY month ASC", created1, created2])
self.connection.select_all r
This protects you from SQL injections.
Since you are not using named binds, you would do it like this. This works in Rails 4.2.
ActiveRecord::Base.connection.select_all(
"SELECT MONTH(created) AS month, YEAR(created) AS year FROM orders WHERE created>=$1 AND created<=$2 GROUP BY month ORDER BY month ASC",
nil,
[[nil,'2016-01-01 12:30'],[nil,'2016-01-01 15:30']]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With