method

references

references(*args)
public

Adds a reference. Optionally adds a type column, if :polymorphic option is provided. references and belongs_to are acceptable. The reference column will be an integer by default, the :type option can be used to specify a different type. A foreign key will be created if a foreign_key option is passed.

t.references(:user)
t.references(:user, type: "string")
t.belongs_to(:supplier, polymorphic: true)

See SchemaStatements#add_reference

2Notes

Doesn't add an index

avit · Aug 22, 20084 thanks

Typically you will want to have an index on foreign keys but this method doesn't assume that. Outside of the create_table block you should follow this with add_index :

add_index :table_name, :goat_id
# and, if polymorphic:
add_index :table_name, :goat_type

add index directly

apsoto · Apr 23, 2015

You can add an index now directly on the foreign_key :

t.references(:user, index: true)