index: テーブルの中の特定のカラムを複製し検索を早めるためにあるんだとか。
references: t.references :userでuser_idカラムを作成し、user_idにインデックスを貼る。(外部キー制約は付けられない)
foreign_key: true: 外部キー制約を貼る。存在しないUserのidがuser_idに登録されるのを防ぐ。親テーブルのレコードを消しちゃうミス防止。
add_foreign_key(:articles, :users)はインデックスが無い場合、インデックスを貼る、ある場合は使い回す。なので、外部キー制約を付ける→インデックスを貼るという順番はだめ。
rails g model article body:text user:references とすると
migrationfile.rb
class CreateArticles < ActiveRecord::Migration[5.2]
def change
create_table :articles do |t|
t.text :body
t.references :user, foreign_key: true
t.timestamps
end
end
end