From cfb24586b811177666cf0d085e3ab111195fb3ff Mon Sep 17 00:00:00 2001 From: Aleksey Magusev Date: Mon, 2 Jul 2012 23:41:49 +0400 Subject: Add references schema statements Examples: add_reference :products, :supplier, polymorphic: true, index: true remove_reference :products, :user `add_belongs_to` and `remove_belongs_to` are acceptable. --- .../abstract/schema_statements.rb | 37 ++++++++++++++++++++++ 1 file changed, 37 insertions(+) (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 2b0ba2f479..8e43193f4b 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -441,6 +441,43 @@ module ActiveRecord indexes(table_name).detect { |i| i.name == index_name } end + # Adds a reference. Optionally adds a +type+ column, if :polymorphic option is provided. + # add_reference and add_belongs_to are acceptable. + # + # ====== Create a user_id column + # add_reference(:products, :user) + # + # ====== Create a supplier_id and supplier_type columns + # add_belongs_to(:products, :supplier, polymorphic: true) + # + # ====== Create a supplier_id, supplier_type columns and appropriate index + # add_reference(:products, :supplier, polymorphic: true, index: true) + # + 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) + 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 : nil) if index_options + end + alias :add_belongs_to :add_reference + + # Removes the reference(s). Also removes a +type+ column if one exists. + # remove_reference, remove_references and remove_belongs_to are acceptable. + # + # ====== Remove the reference + # remove_reference(:products, :user, index: true) + # + # ====== Remove polymorphic reference + # remove_reference(:products, :supplier, polymorphic: true) + # + def remove_reference(table_name, ref_name, options = {}) + polymorphic = options.delete(:polymorphic) + remove_column(table_name, "#{ref_name}_id") + remove_column(table_name, "#{ref_name}_type") if polymorphic + end + alias :remove_belongs_to :remove_reference + # Returns a string of CREATE TABLE SQL statement(s) for recreating the # entire structure of the database. def structure_dump -- cgit v1.2.3