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 1 year has passed since last update.

N+1問題をincludesメソッドで解決

Last updated at Posted at 2022-10-27

N+1問題とは、アソシエーションを利用した場合に限り、データベースへのアクセス回数が多くなってしまう問題のこと。

モデル名.all

としてしまうと、N+1問題にひっかかる。
それを解消するためにincludesメソッドがある。

モデル名.includes(:紐付くモデル名)

と書けばよい。

例:フリマアプリ

class ItemsController < ApplicationController

def index
    @items = Item.includes(:user)
  end

で、ビューでeachメソッドを使ってインスタンスを取り出す。

app/views/items/index.html.erb

 <% @items.each do |item| %>
      <%= item.text %>
      <%= item.name %>
  <% 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?