instance method add_reference

Ruby on Rails 4.2.9

Since v4.0.13

Available in: v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

add_reference(table_name, ref_name, options = {})

Adds a reference. The reference column is an integer by default, the :type option can be used to specify a different type. Optionally adds a _type column, if :polymorphic option is provided. add_reference and add_belongs_to are acceptable.

The options hash can include the following keys:

:type

The reference column type. Defaults to :integer.

:index

Add an appropriate index. Defaults to false.

:foreign_key

Add an appropriate foreign key. Defaults to false.

:polymorphic

Wether an additional _type column should be added. Defaults to false.

Create a user_id integer column
add_reference(:products, :user)
Create a user_id string column
add_reference(:products, :user, type: :string)
Create supplier_id, supplier_type columns and appropriate index
add_reference(:products, :supplier, polymorphic: true, index: true)

Parameters

table_name req
ref_name req
options opt = {}
Source
# File activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb, line 667
      def add_reference(table_name, ref_name, options = {})
        polymorphic = options.delete(:polymorphic)
        index_options = options.delete(:index)
        type = options.delete(:type) || :integer
        foreign_key_options = options.delete(:foreign_key)

        if polymorphic && foreign_key_options
          raise ArgumentError, "Cannot add a foreign key to a polymorphic relation"
        end

        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[type id].map{ |t| "#{ref_name}_#{t}" } : "#{ref_name}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options
        if foreign_key_options
          to_table = Base.pluralize_table_names ? ref_name.to_s.pluralize : ref_name
          add_foreign_key(table_name, to_table, foreign_key_options.is_a?(Hash) ? foreign_key_options : {})
        end
      end

Defined in activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb line 667 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::ConnectionAdapters::SchemaStatements

Type at least 2 characters to search.

↑↓ navigate · open · esc close