0

I have the following db/migrate ruby file. When I tried rake db:migrate, it gave error.

class CreateEmployers < ActiveRecord::Migration
  def self.up
            create_table :employers, {:primary_key => 'emp_id'} do |t|
            t.column :emp_name, :string, :limit => 100, :null => false  #validate
            t.column :company_id, :int, :null => false
            t.column :location, :string, :limit => 200, :null => false  #validate
            t.column :registered_date, :datetime
            t.column :is_verified, :boolean, :default => false, :null => false
            t.column :is_blacklisted, :boolean, :default => false, :null => false
            t.column :emp_grade, :string, :default => 'average', :null => false
            t.timestamps
                end
        end

        execute "ALTER TABLE `employers` 
  ADD CONSTRAINT `FK_EMPLOYERS_COMPANIES`
  FOREIGN KEY (`company_id` )
  REFERENCES `companies` (`company_id` )
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;"

        def self.down
                drop_table :employers
        end
end

I got the following error when I ran rake db:migrate. It was okay if I removed execute part.

-- execute("ALTER TABLE `employers` \n  ADD CONSTRAINT `FK_EMPLOYERS_COMPANIES`\n  FOREIGN KEY (`company_id` )\n  REFERENCES `companies` (`company_id` )\n  ON DELETE NO ACTION\n  ON UPDATE NO ACTION;")
rake aborted!
An error has occurred, all later migrations canceled:

Mysql2::Error: Table 'test.employers' doesn't exist: ALTER TABLE `employers` 
  ADD CONSTRAINT `FK_EMPLOYERS_COMPANIES`
  FOREIGN KEY (`company_id` )
  REFERENCES `companies` (`company_id` )
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

Companies table was already created and company_id was set as primary key (int(11), not null and auto increment).

ruby version is 2.0.0p0 and mysql version is 5.5.31

Did I do something wrong?

Lwin Htoo Ko
  • 2,326
  • 4
  • 26
  • 38

1 Answers1

2

You need to move the execute bit into self.up

Wei
  • 1,252
  • 13
  • 19