add_reference
![Wide documentation Importance_3](https://d2vfyqvduarcvs.cloudfront.net/images/importance_3.png?1349367920)
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2 (0)
- 4.1.8 (0)
- 4.2.1 (13)
- 4.2.7 (15)
- 4.2.9 (0)
- 5.0.0.1 (38)
- 5.1.7 (0)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (9)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (-3)
- 7.1.3.4 (0)
- What's this?
add_reference(table_name, ref_name, **options)
public
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. #add_reference and #add_belongs_to are acceptable.
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.
- :polymorphic
-
Whether an additional _type column should be added. Defaults to false.
- :null
-
Whether the column allows nulls. Defaults to true.
Create a user_id bigint 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)
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})
![Default_avatar_30](https://www.gravatar.com/avatar/a1ffa5e1a9980ad0cd80ed05a7c3f0a0?default=http://apidock.com/images/default_avatar_30.png&size=30)
foreign_key option
It is also possible to specify that add_foreign_key should be added to the schema:
add_reference(:products, :supplier, foreign_key: true)