无法删除外键约束

时间:2010-09-10 15:49:16

标签: mysql ruby-on-rails

我在rails 2.3.9上使用ruby。 rake db:migrate成功通过。但是,当我运行rake db:migrate:redo来测试向下部分时,我收到错误消息。我正在使用Innodb的mysql。

class AddConstraints < ActiveRecord::Migration
  def self.up
    ActiveRecord::Base.connection.execute <<-EOS
      ALTER TABLE venues
      ADD CONSTRAINT FOREIGN KEY (city_id)
        REFERENCES cities (id)
        ON DELETE restrict
        ON UPDATE cascade
    EOS
  end

  def self.down
    ActiveRecord::Base.connection.execute <<-EOS
      ALTER TABLE venues DROP FOREIGN KEY (city_id)
    EOS
  end
end

我收到的错误消息是

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 '(city_id)' at line 1:       
ALTER TABLE venues DROP FOREIGN KEY (city_id)

2 个答案:

答案 0 :(得分:2)

首先,您应该在FOREIGN KEY之后省略括号。其次,您必须告诉mysql要删除的fk约束的名称,而不是受该约束影响的列的名称。如果您运行SHOW CREATE TABLE venues,则可以找到约束的名称 - 可能类似于venues_ibfk_1或类似名称。将此名称用于ALTER TABLE语句,例如ALTER TABLE venues DROP FOREIGN KEY venues_ibfk_1

答案 1 :(得分:0)

也许从声明中删除括号?快速谷歌显示MySQL文档中没有使用括号的语句。