ActionRecord 中有一个名为 index_exists?
的函数,但 Rails 4.2.7 上没有 foreign_key_exists?
。
因此,当我在某些数据库上调用 remove_foreign_key :parties, :franchise_groups
时,它会崩溃。
我应该使用什么?
<小时/>更新
我的代码
class RemoveForeignKey < ActiveRecord::Migration
def up
if foreign_key_exists?(:parties, :franchise_groups)
remove_foreign_key :parties, :franchise_groups
end
end
end
报错
== 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'
最佳答案
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")
或者,您可以使用 foreign_keys
:
if foreign_keys(:table_name).include?(foreign_key_name)
# do stuff
end
关于ruby-on-rails - 如果 Ruby on Rails 中存在外键,如何删除它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40467851/