Rails MySQL临时表错误

时间:2015-03-28 21:21:36

标签: mysql ruby-on-rails

我正在尝试在rails中构建一个临时表,给定下面定义的操作:

 def testCreate
    insert = 'CREATE TEMPORARY TABLE test (
              location varchar(10)
              );

              CREATE TEMPORARY TABLE test2 (
              campaign varchar(10)
              );

              INSERT INTO test
              VALUES' +  params[:insert_location_csv].to_s + ';

              INSERT INTO test2
              VALUES(' + params[:campaign_id].to_s + ');

              INSERT INTO campaign_locations(campaign_id, location_id, created_at, updated_at)
              select 
              a.campaign  as campaign_id
              ,b.location as location_id
              ,NOW()      as created_at
              ,NOW()      as updated_at
              from test2 a
                cross join test b'

    ActiveRecord::Base.connection.execute(insert)
end

在MySQL工作台中,查询执行正常,但在尝试通过路径访问此操作时:http://localhost:3000/testCreate/70/(101),(102)错误显示如下:

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE TEMPORARY TABLE test2 ( campaign varchar(10) ); INSERT' at line 5: CREATE TEMPORARY TABLE test ( location varchar(10) ); CREATE TEMPORARY TABLE test2 ( campaign varchar(10) ); INSERT INTO test VALUES(101),(102); INSERT INTO test2 VALUES(70); INSERT INTO campaign_locations(campaign_id, location_id, created_at, updated_at) select a.campaign as campaign_id ,b.location as location_id ,NOW() as created_at ,NOW() as updated_at from test2 a cross join test b

如何防止发生此错误?

1 个答案:

答案 0 :(得分:1)

传递一个有效的sql查询ActiveRecord::Base.connection.execute方法。您正在传递一组SQL查询并期望它在一次调用中工作。

以下内容应该有效:

create_tmp_table = 'CREATE TEMPORARY TABLE test (
          location varchar(10)
          );

 ActiveRecord::Base.connection.execute(create_tmp_table)

文档:http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-execute