From d074b821489b6d58101d1474dd514990f4bdf0fa Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Tue, 10 Jun 2014 15:29:19 +0200 Subject: fk: infere column name from table names. This allows to create and remove foreign keys without specifying a column. --- .../connection_adapters/abstract/schema_statements.rb | 18 ++++++++++++++---- .../lib/active_record/migration/command_recorder.rb | 4 +++- 2 files changed, 17 insertions(+), 5 deletions(-) (limited to 'activerecord/lib') 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 fe752126ad..0f2af2c6d2 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -647,10 +647,11 @@ module ActiveRecord end def add_foreign_key(from_table, to_table, options = {}) + options[:column] ||= foreign_key_column_for(to_table) primary_key = options.fetch(:primary_key, "id") options = { - column: options.fetch(:column), + column: options[:column], primary_key: primary_key, name: foreign_key_name(from_table, options), dependent: options.fetch(:dependent, nil) @@ -661,17 +662,26 @@ module ActiveRecord execute schema_creation.accept at end - def remove_foreign_key(from_table, options = {}) + def remove_foreign_key(from_table, options_or_to_table = {}) + 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 + at = create_alter_table from_table at.drop_foreign_key foreign_key_name(from_table, options) execute schema_creation.accept at end + def foreign_key_column_for(table_name) # :nodoc: + "#{table_name.to_s.singularize}_id" + end + def foreign_key_name(table_name, options) # :nodoc: options.fetch(:name) do - column_name = options.fetch(:column) - "#{table_name}_#{column_name}_fk" + "#{table_name}_#{options.fetch(:column)}_fk" end end diff --git a/activerecord/lib/active_record/migration/command_recorder.rb b/activerecord/lib/active_record/migration/command_recorder.rb index bd66c941a2..ad726a3c02 100644 --- a/activerecord/lib/active_record/migration/command_recorder.rb +++ b/activerecord/lib/active_record/migration/command_recorder.rb @@ -170,13 +170,15 @@ module ActiveRecord end def invert_add_foreign_key(args) - from_table, _to_table, add_options = *args + from_table, to_table, add_options = *args add_options ||= {} if add_options[:name] options = {name: add_options[:name]} elsif add_options[:column] options = {column: add_options[:column]} + else + options = to_table end [:remove_foreign_key, [from_table, options]] -- cgit v1.2.3