1
1

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 5 years have passed since last update.

MYSQL学んだ事まとめ

Last updated at Posted at 2018-09-01

MYSQLに関して、学んだことを追記していきます。

テーブルにカラムを追加する方法

【参考】add_column-リファレンス

カラムを追加するマイグレーションファイルを作成するためには、下記のコマンドを実行します。

$ rails g migration Addカラム名To追加先テーブル名 追加するカラム名:型

例えば、userの自己紹介を保存するためのカラム、nicknameカラムをusersテーブルにtext型で追加したいとします。その時は、以下の例のように書きます。

$ rails g migration AddNicknameToUsers introduction:text

この時、「Add」「Nickname」「To」「Users」と、単語の頭文字が大文字になっていることに注意。

add_column

add_columnをマイグレーションファイルのchangeメソッド内に書くとカラムの追加ができます。記述方法は以下です。

add_column :テーブル名, :カラム名, :カラムの型

add_columnを書き終えたら、マイグレーションしましょう。

逆に、テーブルから不要なカラムを削除する場合

$ rails g migration Removeカラム名From削除元テーブル名 削除するカラム名:型

$ rake db:migrate

n+1問題の解消方法

includesメソッド

指定された関連モデルをまとめて取得することで、SQLの発行回数を減らすことができます。書き方は、includes(:モデル名)とします。引数で、関連モデルをシンボル型(接頭に:がつく型)で指定します。

例えばTwitterだと、
usersテーブルとtweetsテーブルの間には以下の図のような関係があります。tweetsテーブルのレコードは必ず1つのusersテーブルのレコードに属しているので、includesメソッドを利用することで、tweetsテーブルのレコードを取得する段階で関連するusersテーブルのレコードも一度に取得してしまえば良い

image.png

TweetsController.rb

class TweetsController < ApplicationController

  def index
    @tweets = Tweet.includes(:user).page(params[:page]).per(5).order("created_at DESC")
  end

  #以下省略

end
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?