From fdf371ab0697d43c7eec66418edda9017be9b75b Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Mon, 4 May 2015 22:43:07 +0900 Subject: Support for foreign keys in create table If foreign keys specified in create table, generated SQL is slightly more efficient. Definition: ``` create_table :testings do |t| t.references :testing_parent, foreign_key: true end ``` Before: ``` CREATE TABLE "testings" ("id" serial primary key, "testing_parent_id" integer); ALTER TABLE "testings" ADD CONSTRAINT "fk_rails_a196c353b2" FOREIGN KEY ("testing_parent_id") REFERENCES "testing_parents" ("id"); ``` After: ``` CREATE TABLE "testings" ("id" serial primary key, "testing_parent_id" integer, CONSTRAINT "fk_rails_a196c353b2" FOREIGN KEY ("testing_parent_id") REFERENCES "testing_parents" ("id")); ``` --- .../abstract/schema_statements.rb | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) (limited to 'activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb') 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 035637f7ab..220ac08990 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -260,10 +260,6 @@ module ActiveRecord end end - td.foreign_keys.each_pair do |other_table_name, foreign_key_options| - add_foreign_key(table_name, other_table_name, foreign_key_options) - end - result end @@ -792,15 +788,7 @@ module ActiveRecord def add_foreign_key(from_table, to_table, options = {}) return unless supports_foreign_keys? - options[:column] ||= foreign_key_column_for(to_table) - - options = { - column: options[:column], - primary_key: options[:primary_key], - name: foreign_key_name(from_table, options), - on_delete: options[:on_delete], - on_update: options[:on_update] - } + options = foreign_key_options(from_table, to_table, options) at = create_alter_table from_table at.add_foreign_key to_table, options @@ -868,6 +856,13 @@ module ActiveRecord "#{name.singularize}_id" end + def foreign_key_options(from_table, to_table, options) # :nodoc: + options = options.dup + options[:column] ||= foreign_key_column_for(to_table) + options[:name] ||= foreign_key_name(from_table, options) + options + end + def dump_schema_information #:nodoc: sm_table = ActiveRecord::Migrator.schema_migrations_table_name -- cgit v1.2.3