PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 14, 2022

[FIXED] How do I create a Rails migration that updates a foreign key with an on-delete cascade constraint?

 April 14, 2022     cascade, constraints, foreign-keys, migration, ruby-on-rails-4     No comments   

Issue

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?


Solution

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.



Answered By - ekampp
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing