繁体   English   中英

在ActiveRecord Migration中添加外键时出错

[英]Error when adding foreign key in ActiveRecord Migration

我有以下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

我做错什么了吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM