Rails 6.1.4 counter_cache 问题
Rails 6.1.4 counter_cache issue
我开发了具有 Issue 和 IssueStep 模型的简单应用程序。
我不确定我是否错过了 counter_cache 的某些内容,因为对于使用自定义名称和 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
这是你必须做的才能让它发挥作用
- 将
Issue
table 中的计数器列名称更改为 steps_count
- 在
IssueStep
模型中用以下代码替换您的代码
belongs_to :issue, counter_cache: :steps_count
现在您应该可以使用 issue.steps.size
获取缓存值
This is how Rails find the cached column name: link to official source code
我开发了具有 Issue 和 IssueStep 模型的简单应用程序。 我不确定我是否错过了 counter_cache 的某些内容,因为对于使用自定义名称和 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
这是你必须做的才能让它发挥作用
- 将
Issue
table 中的计数器列名称更改为steps_count
- 在
IssueStep
模型中用以下代码替换您的代码
belongs_to :issue, counter_cache: :steps_count
现在您应该可以使用 issue.steps.size
This is how Rails find the cached column name: link to official source code