LoginSignup
2
2

More than 5 years have passed since last update.

ruby on rails の負荷対策

Last updated at Posted at 2016-10-23

ruby on rails で実装していて基本的だが重要な負荷対策が2つあったので、紹介したい。
eager-loadingと、indexの追加です。

eager-loading

eager-loadingは、N+1問題を解決するためにあります。
N+1問題とは、データをDBから取り出そうとするとき、
sqlの処理がN+1回走ってしまう問題です。これを解決するのが、eager-loadingです。

eager-loadingは、事前にデータをロードするというもので、このN+1問題を解決してくれます。

具体的には、userとbookモデルが1対多の関係になっていた場合、以下のようになります。

**book.user.nameで毎回、userを抽出するsqlが発行されてしまう**

@books = Book.all
@books.each do |book|
  puts book.user.name 
end
**eager-loadingで解決できる**

@books = Book.all.includes(:user)
@books.each do |book|
  puts book.user.name 
end

includes(:user)によって事前にローディングして解決できます。

indexの追加

データベースのテーブルからデータを抽出する際、通常は上から順番にデータを見ていき、該当するデータを抽出します。データ量が多いと時間がかかるので、検索しやすいようにしてくれるのがindexになります。

indexの貼り方は以下になります。

**indexの貼り方(migrationファイルに記述)**

class AddIndexToテーブル名 < ActiveRecord::Migration
  def change
    add_index :テーブル名, カラム名
  end
end
2
2
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
2
2