LoginSignup
11
10

More than 5 years have passed since last update.

ActiveRecordで使う named scope は、includes と joins の区別がつく名前をつけると便利そう

Last updated at Posted at 2014-01-22

ActiveRecord::Relationでは、N + 1問題をはじめとしたパフォーマンス問題に当たることが多い。とくに、includes なのか joins なのかの区別が scope で見分けが付くと便利そう。通常、実装を隠蔽すべきだと思うが、こんな命名規を思いついた。

class Xxx < activeRecord::Base
  scope :with_yyy, -> { joins(:yyy) }
  scope :including_zzz, -> { includes(:zzz) }
end

これぐらいが、抽象化を邪魔しないでいいかなと。

もう一段汎用化してみて、

class Xxx < activeRecord::Base
  scope :with, (rel) -> { joins(yyy) }
  scope :including, (rel) -> { includes(zzz) }
end

として、さらに concerns 以下に抜き出してみてもいいが、なんかと名前空間衝突しそう。(試してないので)

みなさんの現場ではどういう名前が付いていますか?

11
10
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
11
10