在ActiveRecord Migration中添加外键时出错

时间:2013-05-02 06:32:07

标签: mysql ruby sinatra rake rails-migrations

我有以下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),而不是null和自动增量)。

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

我做错了吗?

1 个答案:

答案 0 :(得分:2)

您需要将execute位移至self.up