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

Is it possible to track something else with a counter_cache other than the number of objects in an association?


All I am trying to do, is in an easy/light way...whenever the PostsController#Show action is fired, to increment the post.views or post.view_count column. I don't want to have to do anything too heavy.

It feels like the native counter_cache would be perfect...but that is specifically for association object count.

Anyway I can re-purpose that? Or use the underlying concepts in the way I want?


Solution

  • You can't use counter cache directly, but you can use the underlying increment function. See the documentation. To do what you say, you'd want:

    Post.increment_counter(:view_count, post.id)
    

    This issues a single SQL update command.