如何创建使用on-delete级联约束更新外键的Rails迁移?

时间:2016-05-25 21:01:12

标签: ruby-on-rails-4 foreign-keys migration constraints cascade

我正在使用Rails 4.2.3和PostgreSQL数据库。我想编写一个迁移来更新我的一个外键以获得一个on-delete级联约束,所以我创建了以下内容:

class UpdateForeignKeyAddOnDeleteConstraint < ActiveRecord::Migration
  def change
    remove_foreign_key :my_object_times, :my_objects
    add_foreign_key :my_object_times, :my_objects, on_delete: cascade
  end
end

但是当我运行迁移时,我收到以下错误:

$ rake db:migrate
== 20160525203028 UpdateForeignKeyAddOnDeleteConstraint: migrating ============
-- remove_foreign_key(:my_object_times, :my_objects)
   -> 0.0454s
-- cascade()
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

undefined local variable or method `cascade' for #<UpdateForeignKeyAddOnDeleteConstraint:0x007f82f2c71998>
/Users/davea/.rvm/gems/ruby-2.3.0@global/gems/activerecord-4.2.5.1/lib/active_record/migration.rb:664:in `block in method_missing'
/Users/davea/.rvm/gems/ruby-2.3.0@global/gems/activerecord-4.2.5.1/lib/active_record/migration.rb:634:in `block in say_with_time'
/Users/davea/.rvm/gems/ruby-2.3.0@global/gems/activerecord-4.2.5.1/lib/active_record/migration.rb:634:in `say_with_time'
/Users/davea/.rvm/gems/ruby-2.3.0@global/gems/activerecord-4.2.5.1/lib/active_record/migration.rb:654:in `method_missing'

我应该如何编写迁移来更新外键?

1 个答案:

答案 0 :(得分:16)

您需要更改此行,

add_foreign_key :my_object_times, :my_objects, on_delete: cascade

有了这个:

add_foreign_key :my_object_times, :my_objects, on_delete: :cascade

简单的区别是cascade应该是符号(:cascade)或字符串('cascade')。

希望这会有所帮助。

问候,