From 6d327dbc0cd7969375e14a56c0a9bc6a7c847056 Mon Sep 17 00:00:00 2001 From: Andrey Novikov Date: Sat, 19 Jul 2014 23:38:38 +0400 Subject: Allow to specify a type for foreign key column in migrations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [Andrey Novikov & Ɓukasz Sarnacki] --- .../connection_adapters/abstract/schema_definitions.rb | 9 ++++++++- .../connection_adapters/abstract/schema_statements.rb | 3 ++- 2 files changed, 10 insertions(+), 2 deletions(-) (limited to 'activerecord/lib') 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 98e6795f10..d51bf022a4 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -280,12 +280,19 @@ module ActiveRecord column(:updated_at, :datetime, options) end + # Adds an appropriately-named _id column as :integer (or whatever :type option specifies), + # plus a corresponding _type column if the :polymorphic option is supplied. If :polymorphic + # is a hash of options, these will be used when creating the _type column. The :index option + # will also create an index, similar to calling add_index. + # + # references :tagger, polymorphic: true, index: true, type: :uuid def references(*args) options = args.extract_options! polymorphic = options.delete(:polymorphic) index_options = options.delete(:index) + type = options.delete(:type) || :integer args.each do |col| - column("#{col}_id", :integer, options) + column("#{col}_id", type, options) column("#{col}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic index(polymorphic ? %w(id type).map { |t| "#{col}_#{t}" } : "#{col}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options end 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 5814c2b711..8ecb7c0506 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -619,7 +619,8 @@ module ActiveRecord def add_reference(table_name, ref_name, options = {}) polymorphic = options.delete(:polymorphic) index_options = options.delete(:index) - add_column(table_name, "#{ref_name}_id", :integer, options) + type = options.delete(:type) || :integer + add_column(table_name, "#{ref_name}_id", type, options) add_column(table_name, "#{ref_name}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic add_index(table_name, polymorphic ? %w[id type].map{ |t| "#{ref_name}_#{t}" } : "#{ref_name}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options end -- cgit v1.2.3