参考
以下のページを参考にさせていただきました。ありがとうございます。
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`