[英]Rails Counter Cache with Active Storage
我有一个Account
model,其中有 3 个附件,使用 Active Storage, has_many_attached:attachments
。
我想知道该帐户有多少附件,最有效的方法(也称为无连接)
我找到的唯一解决方案是Account.last.attachments.count
或.size
,但它进行了两个查询:一个用于帐户,一个使用 active_storage_attachments 表。
有没有办法计算缓存附件的数量?
先感谢您
编辑
当然我可以设置自己的数据库字段并统计,我想知道有没有默认的
编辑
我试着做has_many_attached:attachments, counter_cache: true
,但它给出了一个错误
我有一个 model 有 7 个文件附件的类似问题,我需要使用计数器缓存而不是数据库查询来计数。 诀窍是你必须在子 model 中指定计数器缓存引用,在我的例子中它有belongs_to:ParentModel
- ActiveStorage::Attachment
。 ActiveStorage::Attachment
是 Rails 的“幕后”model,所以我猴子修补了它。 但是我没有通过添加counter_cache: :true
来实现计数器缓存,而是决定通过回调来实现它。 我为具有以下结构的ParentModel
创建了一个模块:
module ParenModel::ModuleName
extend ActiveSupport::Concern
class ActiveStorage::Attachment
require 'active_record/counter_cache'
before_create :after_create_action, if: :record_parent_model?
before_destroy :after_destroy_action, if: :record_parent_model?
def after_create_action
ParentModel.increment_counter(:attachments_count, record_id, touch: true)
end
def after_destroy_action
ParentModel.decrement_counter(:attachments_count, record_id, touch: true)
end
def record_parent_model?
record_type == 'ParentModel'
end
end
end
我创建了一个迁移以将:attachments_count
列添加到 ParentModel 中,就像直接计数器缓存实现一样。
也许,您可以尝试使用 CounterCache ? https://api.rubyonrails.org/classes/ActiveRecord/CounterCache/ClassMethods.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.