7

据我所知,应该可以在 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]])

但可悲的是,这根本不起作用。无论我尝试使用什么格式,$1and$2都不会被绑定数组中的相应值替换。

我还有什么需要注意的吗?

4

3 回答 3

6

您应该sanitize_sql_array在模型中使用,如下所示:

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

这可以保护您免受 SQL 注入。

于 2013-07-08T09:52:02.307 回答
1

由于您没有使用命名绑定,因此您可以这样做。这适用于 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']]
)
于 2017-04-29T01:37:52.247 回答
-14

我不明白您是否尝试使用变量,但是使用变量很容易,您错误地使用了它们

像这样使用它:

ActiveRecord::Base.connection.select_all("SELECT MONTH(created) AS month, YEAR(created) AS year FROM orders WHERE created>=#{v1} AND created<=#{v2} GROUP BY month ORDER BY month ASC",nil,[['created',1],['created',2]])

其中 v1 和 v2 是变量。让我知道你是否正在尝试其他东西

谢谢

于 2012-10-06T02:41:27.117 回答