在执行块中具有多个SQL语句的Rails和MySQL语法错误 [英] Rails and MySQL syntax error with multiple SQL statements in an execute block
本文介绍了在执行块中具有多个SQL语句的Rails和MySQL语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在使用MySQL的应用程序的Rails迁移中,我具有以下代码:
I have the following code in a Rails migration for an app that uses MySQL:
execute <<-SQL
ALTER TABLE properties
ADD name VARCHAR(255) NOT NULL;
ALTER TABLE properties
ADD CONSTRAINT fk_properties_name
FOREIGN KEY (name)
REFERENCES valid_property_names (property_name);
SQL
运行迁移时,出现以下错误:
When I run the migration, I get the following error:
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 'ALTER TABLE properties
为什么会出现此错误以及如何解决?
Why am I getting this error and how do I fix it?
推荐答案
这里的问题是,当同一执行块中有多个SQL命令时,Rails Mysql2数据库适配器会阻塞.以下将正常运行:
The problem here is that the Rails Mysql2 database adapter chokes when there are multiple SQL commands within the same execute block. The following will run fine:
execute <<-SQL
ALTER TABLE properties
ADD name VARCHAR(255) NOT NULL;
SQL
execute <<-SQL
ALTER TABLE properties
ADD CONSTRAINT fk_properties_name
FOREIGN KEY (name)
REFERENCES valid_property_names (property_name);
SQL
如果您是将PostgreSQL与Rails一起使用,则此行为可能会使您感到困惑,因为Postgres适配器没有相同的限制.
This behavior may confuse you if you're coming from using PostgreSQL with Rails since the Postgres adapter doesn't have the same limitation.
这篇关于在执行块中具有多个SQL语句的Rails和MySQL语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文