Rails 3 connection.execute IN语句参数数组语法

时间:2012-08-31 14:08:55

标签: mysql ruby-on-rails ruby-on-rails-3 sql-parametrized-query

我有一个关于Rails 3 ActiveRecord :: Base.connection.execute方法和参数的语法问题,我想用它。我一直在与这个斗争几个小时,似乎没有在互联网上找到这个具体问题的任何答案。

数据库是MySQL。

我需要通过SELECT和IN条件语句创建一个临时表,其中IN应该检查的值列表是一个参数 - rails Array。代码如下:

arr = [1,2,3]
ActiveRecord::Base.connection.execute("CREATE TEMPORARY TABLE things SELECT * FROM objects WHERE objects.id IN #{arr}") 

我收到MySQL语法错误!

ActiveRecord::Base.connection.execute("CREATE TEMPORARY TABLE things SELECT * FROM objects WHERE objects.id IN #{(arr)}") 

再次发生MySQL语法错误!

ActiveRecord::Base.connection.execute("CREATE TEMPORARY TABLE things SELECT * FROM objects WHERE objects.id IN (#{arr})") 

MySQL语法错误

以上尝试对应于此问题答案: How to execute arbitrary parameterized SQL in rails

我甚至尝试以与find_by_sql类似的方式使用,但仍然出现错误:

ActiveRecord::Base.connection.execute(["CREATE TEMPORARY TABLE things SELECT * FROM objects WHERE objects.id IN (:ids)",{:ids => arr }]) - obviously, I get an MySQL error. 

我错过了一些明显的东西吗?请帮忙!我完全需要这种方式(例如,创建具有这种条件的临时表),否则基于此的更复杂的查询将无法工作。谢谢!

2 个答案:

答案 0 :(得分:2)

这是使用Rails查询清理的另一个选项

arr = [1,2,3]
query = "SELECT * FROM objects where id IN (?)"
query = ActiveRecord::Base.send :sanitize_sql_array, [query, arr]
ActiveRecord::Base.connection.execute(query)

答案 1 :(得分:1)

如果您转换arr.to_s,则会获得"[1, 2, 3]"

我认为arr.join(', ')应该有用。

ActiveRecord::Base.connection.execute("CREATE TEMPORARY TABLE things SELECT * FROM objects WHERE objects.id IN (#{arr.join(', ')})")