ベルリンのITスタートアップで働くジャバ・ザ・ハットリの日記

日本→シンガポール→ベルリンへと流れ着いたソフトウェアエンジニアのブログ

海外転職の面接で英語で聞かれるRubyとRailsの質問事例とそれを会話で対処する方法 - その3

移転しました。

前回のつづき。

【問題3】

What’s the issue with the controller code below? How would you fix it?

class CommentsController < ApplicationController
  def users_comments
    posts = Post.all
    comments = posts.map(&:comments).flatten
    @user_comments = comments.select do |comment|
      comment.author.username == params[:username]
    end
  end
end

これはなにも「このコードをリファクタリングしてくれ」ってことではない。問題の箇所と解決方法を英語で話すだけ。

【解答例3】

This is a classic example of the notorious “n+1” bug. The first line will retrieve all of the Post objects from the database, but then the very next line will make an additional request for each Post to retrieve the corresponding Comment objects. To make matters worse, this code is then making even more database requests in order to retrieve the Author of each Comment.

This can all be avoided by changing the first line in the method to:

posts = Post.includes(comments: [:author]).all

This tells ActiveRecord to retrieve the corresponding Comment and Author records from the database immediately after the initial request for all Posts, thereby reducing the number of database requests to just three.

まー典型的なN+1問題だね(a classic example of the notorious “n+1” bug)、と指摘できれば、それでもうほぼ正解。
解答例として

posts = Post.includes(:comments).all

としても「いや、もう1段階あるんだけど」ぐらいは指摘されるかもしれない。
とにかくN+1問題に対処した経験があって、データベースのパフォーマンスにも気を使える技術レベルですよ、とアピールすることが肝心。
会話の中で「アタシはGemでBulletとか入れて、デバッグしてるんだよね。あれがあったらN+1が見つかりやすいから。あんたの会社ではナニ使ってんの?」とか質問していろいろ聞くべし。そうした会話の中でその会社の現場の様子なども把握できるし、なにより応募者の技術レベルが「それなりに分かってるレベル」であることが証明できる。

次回につづく。

もっと詳しくエンジニア転職のコツとか書いてる本。

tango-ruby.hatenablog.com

tango-ruby.hatenablog.com

tango-ruby.hatenablog.com

tango-ruby.hatenablog.com