spree/spree — pull request #5828 by wuboy0307 (2014-12-24 03:29:44+00:00)
Title: add hook for additional eager load relationship

For spree extensions, sometimes you will add customized relationship to product.
However, there is not a hook for extensions to add "includes" eager load statement to avoid n+1 query issue.
For example, if I include spree_i18n extension without override anything and go to /products.
It will look up translations for each products:
```
Spree::Product::Translation Load (0.4ms) SELECT `spree_product_translations`.* FROM `spree_product_translations` WHERE `spree_product_translations`.`spree_product_id` = 5
Spree::Product::Translation Load (0.4ms) SELECT `spree_product_translations`.* FROM `spree_product_translations` WHERE `spree_product_translations`.`spree_product_id` = 4
... etc
```

That's pretty bad for performance. So I add a preference "additional_eagerload_scopes" and a hook for base_scope. You can add your dynamic eager load relationships.

For spree_i18n, I can just make a initializer like this:
```
Spree::Config[:additional_eagerload_scopes] ||= []
Spree::Config[:additional_eagerload_scopes].push(:translations) if defined?(SpreeI18n)
```

and SQL will become eager load one:
```
Spree::Product::Translation Load (0.5ms) SELECT `spree_product_translations`.* FROM `spree_product_translations` WHERE `spree_product_translations`.`spree_product_id` IN (5, 4, 26, 2, 3, 13, 28, 27, 17, 8, 9, 14)
```