Rails Counter Caches

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

You can actually see the difference in performance with a small DB. On 13:53 we can infer that the update took 0.0396s (total migration time - add column time) and on 18:44 it took 0.0002s to do the same change.

Also, you can call user.forum_posts.size and it will default to the counter_cache column instead of querying the database, and if someone drop the counter cache you don't have to change the view

gmmcal
Автор

This is a pretty good tutorial. Thanks for sharing!

mauriciofmartinez
Автор

Chris, Rails guides say that "Rails will keep the cache value up to date, and then return that value in response to the size method." So you should be using #size method instead of #forum_posts_count. Without counter_cache: true in your model if you do User.last.forum_posts.size (or whatever model you have) it will trigger SELECT COUNT(*) FROM ForumPosts. Come out of the console, add counter_cache: true, open console and run User.last.forum_posts.size again and you will see that no SELECT COUNT(*) FROM was triggered. Same happens in your view. If you have 10 000 users, without counter_cache: true you will see 10 000 COUNT(*) in your logs whereas with counter_cache: true you will see no COUNT(*).

trailblazer_nomad
Автор

Thanks, bro. This has been really helpful

mosesoloo
Автор

I did not see when he create the forum_thread, is it already created?

ercntreras