diff options
author | Anton <anton.estum@gmail.com> | 2015-01-24 00:20:18 +0300 |
---|---|---|
committer | Anton <anton.estum@gmail.com> | 2015-01-24 00:20:18 +0300 |
commit | 6298ac705da92cc793cbf40dd91484d34e01d255 (patch) | |
tree | 9c54922c6d64b89559d2c2cf42ab8074340a51ea /activerecord/lib | |
parent | 2698e187578d29292eef3e1cb54338a3afd45a1f (diff) | |
download | rails-6298ac705da92cc793cbf40dd91484d34e01d255.tar.gz rails-6298ac705da92cc793cbf40dd91484d34e01d255.tar.bz2 rails-6298ac705da92cc793cbf40dd91484d34e01d255.zip |
Add `foreign_key_exists?` method.
Diffstat (limited to 'activerecord/lib')
-rw-r--r-- | activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb | 4 | ||||
-rw-r--r-- | activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb | 23 |
2 files changed, 27 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index 7eaa89c9a7..a70d93c28b 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -650,6 +650,10 @@ module ActiveRecord def foreign_key(*args) # :nodoc: @base.add_foreign_key(name, *args) end + + def foreign_key_exists?(*args) # :nodoc: + @base.foreign_key_exists?(name, *args) + end private def native diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb index f905669a24..0ca8570d00 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -671,6 +671,29 @@ module ActiveRecord def foreign_keys(table_name) raise NotImplementedError, "foreign_keys is not implemented" end + + # Checks to see if a foreign key exists on a table for a given foreign key definition. + # + # # Check a foreign key exists + # foreign_key_exists?(:accounts, :branches) + # + # # Check a foreign key on specified column exists + # foreign_key_exists?(:accounts, column: :owner_id) + # + # # Check a foreign key with a custom name exists + # foreign_key_exists?(:accounts, name: "special_fk_name") + # + def foreign_key_exists?(from_table, options_or_to_table = {}) + return unless supports_foreign_keys? + + if options_or_to_table.is_a?(Hash) + options = options_or_to_table + else + options = { column: foreign_key_column_for(options_or_to_table) } + end + + foreign_keys(from_table).any? {|fk| options.keys.all? {|key| fk.options[key].to_s == options[key].to_s } } + end # Adds a new foreign key. +from_table+ is the table with the key column, # +to_table+ contains the referenced primary key. |