instance method
add_reference
Ruby on Rails 8.0.4
Since v4.0.13Signature
add_reference(table_name, ref_name, **options)
Adds a reference. The reference column is a bigint by default, the :type option can be used to specify a different type. Optionally adds a _type column, if :polymorphic option is provided.
The options hash can include the following keys:
:type-
The reference column type. Defaults to
:bigint. :index-
Add an appropriate index. Defaults to true. See #add_index for usage of this option.
:foreign_key-
Add an appropriate foreign key constraint. Defaults to false, pass true to add. In case the join table can’t be inferred from the association pass
:to_tablewith the appropriate table name. :polymorphic-
Whether an additional
_typecolumn should be added. Defaults to false. :null-
Whether the column allows nulls. Defaults to true.
Create a user_id bigint column without an index
add_reference(:products, :user, index: false)
Create a user_id string column
add_reference(:products, :user, type: :string)
Create supplier_id, supplier_type columns
add_reference(:products, :supplier, polymorphic: true)
Create a supplier_id column with a unique index
add_reference(:products, :supplier, index: { unique: true })
Create a supplier_id column with a named index
add_reference(:products, :supplier, index: { name: "my_supplier_index" })
Create a supplier_id column and appropriate foreign key
add_reference(:products, :supplier, foreign_key: true)
Create a supplier_id column and a foreign key to the firms table
add_reference(:products, :supplier, foreign_key: { to_table: :firms })
Parameters
-
table_namereq -
ref_namereq -
optionskeyrest
Source
# File activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb, line 1066
def add_reference(table_name, ref_name, **options)
ReferenceDefinition.new(ref_name, **options).add(table_name, self)
end
Defined in activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb line 1066
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::ConnectionAdapters::SchemaStatements