0
0

More than 1 year has passed since last update.

N+1問題

Last updated at Posted at 2021-09-26

データ一個でも1+Nである事を教えてくれる gem 'bullet'

gemを入れる。これ入れればデータ一個でも1+Nを教えてくれる

それがわからず、データを作りまくりました...(でもログが出なかったのでそこは問題にならない。)

コメント機能などのアソシエーションがかかっていたり、関係があるデータを持ってくるとなると発生する

gem
 group :development do
     gem 'bullet'
 end
ターミナル
bundle install

config/enviroments/develop.rbに設定を書く、カスタマイズできる

デプロイ後に, デプロイ自動化する「GitHub Actions」というGitHubのサービスをやったので、if ENV["CI"] != trueを追加した

config/enviroments/develop.rb
Rails.application.configure do

 if ENV["CI"] != true

 #GitHub Actionsを追加していない場合は以下のみでOK
   config.after_initialize do
    Bullet.enable = true
    Bullet.alert = true
    Bullet.bullet_logger = true
    Bullet.console = true
    Bullet.rails_logger = true
    Bullet.add_footer = true
   end

 end
end

N+1問題が出るページにいくとログに

コンソール
user: ec2-user
GET /staff/ostomies/show/2/6
USE eager loading detected
  Comment => [:staff]
  Add to your query: .includes([:staff])
Call stack
  /home/ec2-user/environment/stoma/app/views/staff/ostomies/show.html.erb:50:in `block in _app_views_staff_ostomies_show_html_erb_'
  /home/ec2-user/environment/stoma/app/views/staff/ostomies/show.html.erb:49:in `_app_views_staff_ostomies_show_html_erb_'


^C- Gracefully stopping, waiting for requests to finish

該当行を確認

views/staff/ostomies/show.html.erb
 47       <th>スタッフからのコメント</th>
 48        <td id="staff_comment">
 49         <% @ostomy.comments.each do |comment| %>
 50         <%= comment.staff.name %>
 51         <%= comment.created_at.strftime('%Y/%m/%d') %>
 52         <%= comment.comment %>
 53         <% end %>
 54       </td>
views/staff/ostomies/show.html.erb
 47       <th>スタッフからのコメント</th>includes([:staff]).
 48        <td id="staff_comment">  ↓↓↓↓↓↓#追加
 49         <% @ostomy.comments.includes([:staff]).each do |comment| %> =>>>>ここでデータを全て取りにいく
 50         <%= comment.staff.name %>
 51         <%= comment.created_at.strftime('%Y/%m/%d') %>
 52         <%= comment.comment %>
 53         <% end %>
 54       </td>

N+1  includesがよくわからなかった

@ostomy.comments.each do |comment|でコメント取りに行く→投稿した人のデータ取り行くを繰り返すのでデータ取りに行く回数が増える

includes([:staff])を入れることでまとめて取れるのでスムーズになる

 47       <th>スタッフからのコメント</th>  =>>>>ここでデータ取りいく
 48        <td id="staff_comment">  #追加前
 49         <% @ostomy.comments.each do |comment| %>
 50         <%= comment.staff.name %>   =>>>>ここで[さらに]staffデータ取りいくロスタイム
 51         <%= comment.created_at.strftime('%Y/%m/%d') %>
 52         <%= comment.comment %>
 53         <% end %>
 54       </td>
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