views:

28

answers:

2

I am using ruby on rails 2.3.9. The rake db:migrate passed successfully. However when I run rake db:migrate:redo to test the down part I get error message. I am using mysql with Innodb.

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

The error message I am getting is

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)
A: 

Maybe remove the parentheses from the statement? A quick google showed statements without parentheses being used in the MySQL documentation.

Matthew Schinckel
removing parantheses lead to a different error. Mysql::Error: Error on rename of './eii_development/venues' to './eii_development/#sql2-85-101' (errno: 152): ALTER TABLE venues DROP FOREIGN KEY city_id
Nadal
+1  A: 

First, you should omit the parentheses after FOREIGN KEY. Second, you must tell mysql the name of the fk constraint you want to drop, not the name of the column affected by that constraint. If you run SHOW CREATE TABLE venues, you can find out the name of the constraint - probably something like venues_ibfk_1 or similar. Use this name for the ALTER TABLE statement, e.g. ALTER TABLE venues DROP FOREIGN KEY venues_ibfk_1.

titanoboa
I see. However that means the nake of foreign key will be different for different people. It means there is no clean way to fix this problem using ruby rails. unless I dynamically find the correct foreign_key. Is there a way to tell mysql to create foreign key with a specific name or is it totally upto mysql?
Nadal
Not sure what you mean by "different name for different people". Anyway, you can choose the name of the foreign key when you create it, see http://dev.mysql.com/doc/refman/5.0/en/create-table.html and http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html (or the respective pages for your version of MySQL).
titanoboa