MYSQLに関して、学んだことを追記していきます。
テーブルにカラムを追加する方法
カラムを追加するマイグレーションファイルを作成するためには、下記のコマンドを実行します。
$ 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テーブルのレコードも一度に取得してしまえば良い
class TweetsController < ApplicationController
def index
@tweets = Tweet.includes(:user).page(params[:page]).per(5).order("created_at DESC")
end
#以下省略
end