Rails and MySQL syntax error with multiple SQL statements in an execute block

点点圈 提交于 2019-12-07 08:35:49

问题


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?


回答1:


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

This behavior may confuse you if you're coming from using PostgreSQL with Rails since the Postgres adapter doesn't have the same limitation.



来源:https://stackoverflow.com/questions/24226825/rails-and-mysql-syntax-error-with-multiple-sql-statements-in-an-execute-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!