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 5 years have passed since last update.

Rails ActiveRecordの結合時のクエリの内容について

Last updated at Posted at 2019-08-16

参考

以下のページを参考にさせていただきました。ありがとうございます。
ActiveRecordのjoinsとpreloadとincludesとeager_loadの違い
【Rails】テーブル結合

データ構造

companiesテーブル

id name
1 A社
2 B社

servicesテーブル

id company_id name
1 1 Aアプリ1
2 1 Aアプリ2
3 1 Aアプリ3
4 2 Bの野望

パターン1 all(pluckなし)

companies = Company.all
companies.each do |company|
    company.services
end
SELECT `companies`.* FROM `companies`
SELECT `services`.* FROM `services` WHERE `services`.`company_id` IN (1,2)

パターン2 : all

companies = Company.all
companies.each do |company|
    model.services.pluck(:name).join(',')
end
SELECT `companies`.* FROM `companies`
SELECT `services`.`name` FROM `services` WHERE `services`.`company_id` = 1
SELECT `services`.`name` FROM `services` WHERE `services`.`company_id` = 2

パターン3 : join

companies = Company.joins(:services)
companies.each do |company|
    model.services.pluck(:name).join(',')
end
SELECT `companies`.* FROM `companies` INNER JOIN `services` ON `services`.`company_id` = `companies`.`id`
SELECT `services`.`name` FROM `services` WHERE `services`.`company_id` = 1
SELECT `services`.`name` FROM `services` WHERE `services`.`company_id` = 1
SELECT `services`.`name` FROM `services` WHERE `services`.`company_id` = 1
SELECT `services`.`name` FROM `services` WHERE `services`.`company_id` = 2

パターン4 : preload

companies = Company.preload(:services)
companies.each do |company|
    model.services.pluck(:name).join(',')
end
SELECT `companies`.* FROM `companies`
SELECT `services`.* FROM `services` WHERE `services`.`company_id` IN (1,2)

パターン5 : includes

companies = Company.includes(:services)
companies.each do |company|
    model.services.pluck(:name).join(',')
end
SELECT `companies`.* FROM `companies`
SELECT `services`.* FROM `services` WHERE `services`.`company_id` IN (1,2)

パターン6 : eager_load

companies = Company.includes(:services)
companies.each do |company|
    model.services.pluck(:name).join(',')
end
SELECT **省略** FROM `companies` LEFT OUTER JOIN `services` ON `services`.`company_id` = `companies`.`id`
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?