0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

migrationfile書き方

Last updated at Posted at 2020-10-07

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?