This page looks best with JavaScript enabled

【Rails】eager_load, preload, joins入門

 ·   ·  ☕ 1 分で読めます
✏️

joins

1
2
[1] pry(main)> User.joins(:tags)
  User Load (21.3ms)  SELECT `users`.* FROM `users` INNER JOIN `registered_tags` ON `registered_tags`.`user_id` = `users`.`id` INNER JOIN `tags` ON `tags`.`id` = `registered_tags`.`tag_id`
1
2
3
select *
from tables
inner join other_tables

のオーソドックスな形。

eager_load

1
2
[3] pry(main)> User.eager_load(:tags)
  SQL (0.7ms)  SELECT `users`.`id` AS t0_r0, `users`.`twitter_id` AS t0_r1, `users`.`uuid` AS t0_r2, `users`.`name` AS t0_r3, `users`.`description` AS t0_r4, `users`.`privacy` AS t0_r5, `users`.`role` AS t0_r6, `users`.`created_at` AS t0_r7, `users`.`updated_at` AS t0_r8, `users`.`screen_name` AS t0_r9, `users`.`avatar_url` AS t0_r10, `tags`.`id` AS t1_r0, `tags`.`name` AS t1_r1, `tags`.`created_at` AS t1_r2, `tags`.`updated_at` AS t1_r3 FROM `users` LEFT OUTER JOIN `registered_tags` ON `registered_tags`.`user_id` = `users`.`id` LEFT OUTER JOIN `tags` ON `tags`.`id` = `registered_tags`.`tag_id`
1
2
3
select tables.id, tables.column1, tables.column2, ...
from tables
left outer join other_tables

joinsとの違いは、

  • カラムを全てひとつひとつ取得している
  • inner_joinかleft outer joinか

preload

1
2
3
4
[5] pry(main)> User.preload(:tags)
  User Load (0.4ms)  SELECT `users`.* FROM `users`
  RegisteredTag Load (0.4ms)  SELECT `registered_tags`.* FROM `registered_tags` WHERE `registered_tags`.`user_id` IN (1, 2, 3)
  Tag Load (0.6ms)  SELECT `tags`.* FROM `tags` WHERE `tags`.`id` IN (1, 3, 6, 2, 8)

関連テーブルのデータも全て事前に読み込んでいるだけ。

SQL素人でも分かるテーブル結合(inner joinとouter join)
ActiveRecordのincludes, preload, eager_load の個人的な使い分け | Money Forward Engineers’ Blog
ActiveRecordのjoinsとpreloadとincludesとeager_loadの違い - Qiita

Share on

END
END
@aiandrox

目次