我有一个标签模型,posts_count
其中有一列用作标签具有的帖子数量的计数器缓存:
架构.rb:
t.integer "posts_count", :default => 0, :null => false
标记.rb:
def decrement_tag_counter_cache
Tag.decrement_counter(:posts_count, self.tag.id) if !post.published? || post.decrement_tag_counters?
end
post.rb:
after_save :increment_decrement_tag_counters # covers :save, :create, :update methods
def increment_tag_counters? # if status changes and the previous status wasn't "Published"
status_changed? && changed_attributes["status"] != "Published"
end
def decrement_tag_counters? # if status changes and the previous status was "Published"
status_changed? && changed_attributes["status"] == "Published"
end
def increment_decrement_tag_counters
if published? && increment_tag_counters?
taggings.each { |tagging| tagging.increment_tag_counter_cache }
elsif decrement_tag_counters?
taggings.each { |tagging| tagging.decrement_tag_counter_cache }
end
end
现在的问题是,有时该decrement_tag_counter_cache
方法会posts_count
变为负数(例如-1)。
有没有办法告诉 Rails:使最小值为posts_count
0?因此,如果当前值为 0 并且计数器递减,posts_count
仍将保持为 0?我可以做的另一件事是防止decrement_counter
设置负值。那可能吗?
(这不应该作为验证,而是作为默认行为,因为我不希望出现错误。)