依赖于 Paperclip 的条件计数器缓存

Conditional counter cache dependent on Paperclip

我有一个 counter_culture counter that depends on whether a Paperclip 附件是否已定义:

class Post < ::ActiveRecord::Base
  belongs_to :user

  counter_culture :user, column_name: Proc.new { |p| p.media? ? 'posts_with_photo_count' : nil }
end

问题是当 post 更新销毁 时,计数器不会更新。

我猜应该和Paperclip自己的回调系统有关

我猜到是怎么回事了。这实际上是由于 counter_culturePaperclip.

的回调的流程不匹配

after_update 起,当计数器条件执行时附件尚未处理,p.media? returns false 且计数器未递增。

类似的事情发生在 after_destroy,因为附件在 before_destroy 被销毁。

针对这个问题,我提出了以下解决方案:

counter_culture :user, column_name: Proc.new { |p| (p.photo_file_name? || !p.photo_file_name_was.nil?)  ? 'posts_with_photo_count' : nil }

它基本上考虑了 _file_name 的创建和更新,并验证附件是否在销毁时被清除。