我是Rails的新手,我不明白为什么会收到此错误。
我的Rails应用程序中有一个教学模型,我想使用rails destroy model teaches
删除此模型。但是,当我运行bundle exec rake db:rollback
时,会不断出现此错误Mysql2::Error: Error on rename of './CrimeEducApp_development/#sql-ca1_27' to './CrimeEducApp_development/teaches' (errno: 150 - Foreign key constraint is incorrectly formed): ALTER TABLE teaches DROP PRIMARY KEY;
示教模型没有任何使用其属性作为外键的表,但是示教模型确实具有引用其他表的属性。
模型文件
require 'composite_primary_keys'
class Teach < ApplicationRecord
self.primary_key = :course_id, :certification_number
belongs_to :course, class_name: "Course", foreign_key: "course_id"
belongs_to :worker, class_name: "Worker", foreign_key: "certification_number"
end
迁移档案
class CreateTeaches < ActiveRecord::Migration[5.0]
def up
create_table :teaches , {:id => false} do |t|
t.integer :course_id
t.integer :certification_number
t.timestamps
end
execute "ALTER TABLE teaches ADD PRIMARY KEY(course_id, certification_number);"
execute "ALTER TABLE teaches ADD CONSTRAINT teaches_references_course FOREIGN KEY (course_id) REFERENCES courses(course_id) ON DELETE CASCADE ON UPDATE CASCADE;"
execute "ALTER TABLE teaches ADD CONSTRAINT teaches_references_worker FOREIGN KEY (certification_number) REFERENCES workers(certification_number) ON DELETE CASCADE ON UPDATE CASCADE;"
end
def down
execute "ALTER TABLE teaches DROP PRIMARY KEY;"
execute "ALTER TABLE teaches DROP FOREIGN KEY teaches_references_course;"
execute "ALTER TABLE teaches DROP FOREIGN KEY teaches_references_worker;"
drop_table :teaches
end
end
我可能引用的属性有误吗?
最佳答案
显然,删除主键必须在最后一个execute语句之后(如果不是)。