Search code examples
ruby-on-railsruby-on-rails-3counter-cache

How can I check if counter cache is working okay?


I've done everything what it says on Railscast( http://railscasts.com/episodes/23-counter-cache-column ).

I've done with those setups

  • migration to add new column 'comments_count' to 'community_topics" table, which is parent table.

  • I've added counter_cache: true to models/comment.rb (Now it's just like this belongs_to :commentable, :polymorphic => true, counter_cache: true )

and I have this in my view

<%= community_topic.comment_threads.size %>

As you know, I can't see any difference on its appearance.
How can I know if counter cache is working fine now?


Solution

  • As it says in the RailsCast you reference, you should verify by checking the SQL that is being run via the logs. Before the counter cache you should get a SQL COUNT query something like this:

    SELECT count(*) AS count_all FROM "comment_threads" WHERE ("comment_threads".commentable_id = 61)
    

    and after you should not see one, and instead only see the CommunityTopic loading:

    SELECT * FROM "comment_threads" WHERE id = 61