How to remove a foreign key if it exists in Ruby on Rails?

Is there a function in index_exists? called index_exists? but no foreign_key_exists? on Rails 4.2.7.

Therefore, when I call remove_foreign_key :parties, :franchise_groups in 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 an 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' 
+6
source share
5 answers

but not foreign_key_exists?

Are there foreign_key_exists? :)

Checks if a foreign key exists in the 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 
+4
source

I think you can use something like this

 def up remove_foreign_key :parties, column: :franchise_groups end def down add_foreign_key :parties, :franchise_groups end 
+1
source

It works when connected:

 ActiveRecord::Base.connection.foreign_key_exists?(:parties, :franchise_groups) 
+1
source

There are no foreign_key_exists in Rails 4, so I came up with the following solution:

 remove_foreign_key :events, column: :subscribers_selector_id if foreign_keys(:events).map(&:column).include?("subscribers_selector_id") 
+1
source

Does the My Rails version seem to have no "foreign_key_exists"? (Rails 4.2.6), so I'm using Array # any? to search for the results of "foreign_keys" and determine if this foreign key exists:

 foreign_keys("parties").any?{|k| k[:to_table] == "franchise_groups"} 

You can use it as such:

 if foreign_keys("parties").any?{|k| k[:to_table] == "franchise_groups"} remove_foreign_key :parties, column: :franchise_group_id end 
0
source

Source: https://habr.com/ru/post/1012105/


All Articles