Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

joins雑メモ

joins

用途 隣接しているモデルの属性で絞り込みを行うとき。
具体例 あるブログのポストでホゲ君だけがコメントしているポストだけ集めたい。
条件 コメントのデータは扱わない。

SQL文(クエリ)

Post.joins(:comments).each do |post| post.comments.each do |comment| end end 
 SELECT "posts".* FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"

 Comments Load (0.5ms)  SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ?  [["post_id", 1]]                            

 Comments Load (0.5ms)  SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ?  [["post_id", 1]]                            

:
:
:

コメントがあるポスト取得。
しかしコメントは毎回クエリを実行している。(N+1は解決していない。)

参考
http://blog.scoutapp.com/articles/2017/01/24/activerecord-includes-vs-joins-vs-preload-vs-eager_load-when-and-where

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
0
Help us understand the problem. What are the problem?