Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I drop a foreign key if it exists in Ruby on Rails?

There's a function called index_exists? in ActionRecord, but no foreign_key_exists? on Rails 4.2.7.

So when I call remove_foreign_key :parties, :franchise_groups on some databases it breaks.

What should I use?


Update

My code

class RemoveForeignKey < ActiveRecord::Migration
  def up
    if foreign_key_exists?(:parties, :franchise_groups)
      remove_foreign_key :parties, :franchise_groups
    end
  end
end

gives the error

== 20161107163800 RemoveForeignKey: migrating =================================
-- foreign_key_exists?(:parties, :franchise_groups)
rake aborted!
An error has occurred, all later migrations canceled:

undefined method `foreign_key_exists?' for #<RemoveForeignKey:0x00000007ea0b58>
/home/rje/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7/lib/active_record/migration.rb:664:in `block in method_missing'
like image 362
Richard Avatar asked Nov 07 '16 14:11

Richard


2 Answers

but no foreign_key_exists?

There is foreign_key_exists? :)

Checks to see if a foreign key exists on a table for a given foreign key definition.

# Checks to see if a foreign key exists.
  foreign_key_exists?(:accounts, :branches)

# Checks to see if a foreign key on a specified column exists. foreign_key_exists?(:accounts, column: :owner_id)

# Checks to see if a foreign key with a custom name exists. foreign_key_exists?(:accounts, name: "special_fk_name")

Alternatively, you can use foreign_keys:

if foreign_keys(:table_name).include?(foreign_key_name)
  # do stuff
end
like image 149
Andrey Deineko Avatar answered Nov 15 '22 21:11

Andrey Deineko


Rails 7+ if_exists / if_not_exists options

Rails 7 adds if_exists option to remove_foreign_key in order to not raise an error when the foreign key is already removed.

Rails 7 adds if_not_exists option to add_foreign_key in order to not raise an error when the foreign key is already added.

As a result, a migration can be written in the following way:

class RemoveFranchiseGroupForeignKeysFromParties < ActiveRecord::Migration
  def up
    remove_foreign_key :parties, :franchise_groups, if_exists: true
  end

  def down
    add_foreign_key :parties, :franchise_groups, if_not_exists: true
  end
end

Sources:

  • Add support for if_exists/if_not_exists on remove_foreign_key/add_foreign_key.
  • remove_foreign_key docs.
  • add_foreign_key docs.
like image 26
Marian13 Avatar answered Nov 15 '22 22:11

Marian13