I have a counter_culture counter that depends on whether a Paperclip attachment is defined or not:
class Post < ::ActiveRecord::Base
belongs_to :user
counter_culture :user, column_name: Proc.new { |p| p.media? ? 'posts_with_photo_count' : nil }
end
The issue is that the counter is not updated when the post is either updated nor destroyed.
I guess it should have something to do with Paperclip's own callback system.
I guessed what is happening. It's in fact due to a flow mismatch regarding the callbacks of both counter_culture and Paperclip.
Since on after_update
, the attachment is not already processed when the counter condition executes, p.media?
returns false and the counter is not incremented.
A similar thing happens on after_destroy
, since the attachment is destroyed on before_destroy
.
I came up with the following solution for this issue:
counter_culture :user, column_name: Proc.new { |p| (p.photo_file_name? || !p.photo_file_name_was.nil?) ? 'posts_with_photo_count' : nil }
It basically considers the _file_name
for creates and updates and verifies if the attachment was cleared on destroy.