ruby-on-railscounter-cache

Rails 6.1.4 counter_cache issue


I develop simple app which has Issue and IssueStep models. I'm not sure if I missed something with counter_cache because it not works as expected for relation defined with custom name and class_name.

issue.steps.size - fire count() in DB, why? 
issue.issue_steps.size - uses counter_cache
issue.issue_steps_count - has correct values and I use it now
class IssueStep < ApplicationRecord
  belongs_to :issue, counter_cache: true
end

class Issue < ApplicationRecord
  has_many :steps, class_name: 'IssueStep', foreign_key: 'issue_id', dependent: :destroy
  has_many :issue_steps # added for test only 
end

Solution

  • Here is what you have to do to make it work

    1. Change the counter column name in the Issue table to steps_count
    2. In IssueStep model replace your code with the following
      belongs_to :issue, counter_cache: :steps_count
    

    Now you should be able to to get the cached value using issue.steps.size

    This is how Rails find the cached column name: link to official source code