globalize/globalize — pull request #336 by scarfacedeb (2014-02-19 08:23:55+00:00)
Title: Preload

Beginning of the discussion: https://github.com/globalize/globalize/issues/329

Presently, globalize would fetch all translations when we would access translated attributes:
```
> posts = Post.all
Post Load (0.5ms) SELECT "posts".* FROM "posts"
=> [...] # all posts
> posts.first.title
Post::Translation Load (0.6ms) SELECT "post_translations".* FROM "post_translations" WHERE "post_translations"."post_id" = $1 [["post_id", 2]]
=> "123123"
> posts.first.translations.length
=> 3
```
But if we want to get records that have translation for a specific locale, we would use `with_translations` method, that produces slightly different result.
```
posts = Post.with_translations(:en)
SQL (1.4ms) SELECT "posts"."id" AS t0_r0, "posts"."slug" AS t0_r1, "posts"."created_at" AS t0_r2, "posts"."updated_at" AS t0_r3, "posts"."blog_id" AS t0_r4, "post_translations"."id" AS t1_r0, "post_translations"."post_id" AS t1_r1, "post_translations"."locale" AS t1_r2, "post_translations"."created_at" AS t1_r3, "post_translations"."updated_at" AS t1_r4, "post_translations"."title" AS t1_r5, "post_translations"."body" AS t1_r6 FROM "posts" LEFT OUTER JOIN "post_translations" ON "post_translations"."post_id" = "posts"."id" WHERE "post_translations"."locale" = 'en'
=> [...] # filtered posts
> posts.first.translations.length
=> 1
```
I've got 2 issues with the last case:
1. It uses slow LEFT OUTER JOIN query
2. It's not compatible with default logic and it makes it difficult to get all available translations for returned records.

----

I resolved both of the issues by using `preload`, instead of `includes`.
All not-skipped tests are green.

--

Also, @shioyama wrote in the previous issue that there's no need to use [this ugliness](https://github.com/globalize/globalize/blob/f98a350c1462ea846f9a48929249001e3c68d2c4/lib/globalize/active_record/query_methods.rb#L37), but I'm not sure which sections of code in that file are still relevant. Can somebody take a look at it?