我有一个带有posts_count列的标记模型,它充当标记拥有的帖子数量的计数器缓存:
schema.rb:
t.integer "posts_count", :default => 0, :null => falsetagging.rb:
def decrement_tag_counter_cache
Tag.decrement_counter(:posts_count, self.tag.id) if !post.published? || post.decrement_tag_counters?
endpost.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设置负值。这有可能吗?
(这不应该用作验证,而是作为一种默认行为,因为我不希望出现错误。)
发布于 2012-12-29 09:49:29
可以将验证放在posts_count上,如下所示
validates :posts_count, :numericality => { :greater_than_or_equal_to => 0 }或者你可以做这样的事
before_save :set_posts_count
def set_posts_count
posts_count = 0 if posts_count < 0
end发布于 2014-09-11 04:05:27
这个问题可能会出现,因为据我所知,这个方法没有初始化模型实例,因此它发送了一个像下面这样的直接sql查询:
UPDATE "Tags" SET "posts_counter" = COALESCE("posts_counter", 0) - 1 WHERE "Tags"."id" = 5如果是这样的话,我不知道如何解决这个问题,也许您可以用锁初始化一个模型实例,然后减少计数器,但是锁有其缺点。
发布于 2016-05-25 21:45:20
你可以做这样的事
[posts_count, 0].maxhttps://stackoverflow.com/questions/14080437
复制相似问题