LoginSignup
0
1

More than 1 year has passed since last update.

includesを用いてN+1問題を解消する

Posted at

関連付によって構文が異なるincludesメソッド

N+1問題を解消する目的で、メインページでのfeedメソッドにincludesを導入しました。

伝えられる事としましては、関連付けの種類によってincludesの構文が変わるという事です。

controller.rb
def home
  :
  @feed_items = current_user.feed.page(params[:page])
  :
end

before

user.rb(変更前
def feed
    Work.where(
        "user_id = ? OR user_id IN (?)",
        id,
        Relationship.where(follower_id: id).select(:followed_id)
    )
end

after

user.rb(変更後
def feed
  Work.includes(
    [
      :comments,
      :likes,
      image_attachment: :blob,
      user: { avatar_attachment: :blob },
      illustrations: { photo_attachment: :blob }
    ]
  ).where(
    "user_id = ? OR user_id IN (?)",
    id,
    Relationship.where(follower_id: id).select(:followed_id)
  )
 end

このアプリケーションのER図です。
(自動生成されたものなので見ずらいかもしれません。すいません。

erd

今回は以上です!!
目を通して頂きありがとうございました!!

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