30

I’m using Rails 4.2.3 and a PostgreSQL database. I want to write a migration to update one of my foreign keys to have an on-delete cascade constraint, so I created the following:

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

but when I run the migration I get the error below:

$ 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'

How am I supposed to write my migration to update the foreign key?

oxfist
  • 749
  • 6
  • 22
Dave
  • 15,639
  • 133
  • 442
  • 830

1 Answers1

34

You need to change this line,

add_foreign_key :my_object_times, :my_objects, on_delete: cascade

With this one:

add_foreign_key :my_object_times, :my_objects, on_delete: :cascade

The simple difference is that cascade should be a symbol (:cascade) or a string ('cascade').

See the documentation on add_foreign_key for more info.

I hope this helps.

ekampp
  • 1,904
  • 18
  • 31
  • I used `add_reference :books, :author, type: :uuid, foreign_key: true` to associate that a book belongs_to and author. When I try to delete an author though, I get an foreign key constraint error. In my Rails code I have added `dependent: :destroy` to the author, but I'd like that to be reflected in the schema. Should I remove the foreign key: true and add an add_foreign_key call? Any suggestions on best practice? – Jeffrey Kandel Jul 30 '18 at 23:44
  • 1
    Hi Jeffrey. I suggest that you have a look here on stack overflow regarding the subject (here: https://stackoverflow.com/search?q=rails+dependent+destroy+not+working). If you still can't find your answer I suggest opening a new question here on StackOverflow. People will most likely want code samples and reproduction to help you solve it, and the comments track isn't really good for that. – ekampp Jul 31 '18 at 07:04