LoginSignup
0
0

More than 5 years have passed since last update.

Railsでカラム追加無しにcountのN+1を回避する。

Posted at

countはそのままだと、繰り返しクエリーが発行されてしまう。そのためのカウンターキャッシュだが、
カウンターキャッシュは、カラム追加が必要だし、eager_loadingしても、countは無視される。
ということで、吐き出す直前で、comments_countのメソッドを定義してcount値を追加してあげる。

comments_count = Comment.group("item_id").count #1
items.map{|item| item.instance_eval("def comments_count; @comments_count;end;"); #2
item.instance_variable_set(:@comments_count,comments_count[item.id].to_i);item} #3
item.comments_count # 42

#1 でやっていることは、最初にグループのカウントクエリで、1クエリで全部取ってくる。
#2 でカウンタインスタンスメソッド
#3 でカウンタのセット

メソッドで定義することで、モデル内で処理できるので、後の出力で扱い易い。
同じ要領で特殊な集計結果も持つ場合がある場合にも、同じようにモデル内に入れ込むこともできます。
カウンターキャッシュを持たせるのが重たい場合に、検討の価値があるかと思います。

0
0
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
0
0