0

我有以下 db/migrate ruby​​ 文件。当我尝试rake db:migrate时,它给出了错误。

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

运行时出现以下错误rake db:migrate。如果我删除execute了一部分就可以了。

-- 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;

公司表已经创建,company_id 设置为主键(int(11),不为空且自动递增)。

ruby 版本是 2.0.0p0,mysql 版本是 5.5.31

我做错什么了吗?

4

1 回答 1

2

您需要将execute位移动到self.up

于 2013-05-02T06:34:12.700 回答