我的Post
模型有以下列:
t.datetime "published_at"
t.string "status"
published_at
应该只定义一次(第一次post.status
等于"Published"
):
post.rb:
before_save :publish_post
protected
def publish_post
if self.status == "Published" && self.published_at.nil?
self.published_at = Time.now
end
end
现在,我posts_count
在模型中添加了一个列Tag
:
t.integer "posts_count", :default => 0, :null => false
计数器仅应在post.status
等于时递增和递减"Published"
(不应递增post.status
等于"Draft"
):
标记.rb:
after_save :increment_tag_counter_cache
after_destroy :decrement_tag_counter_cache
private
def increment_tag_counter_cache
if self.post.status == "Published" && self.post.published_at.nil?
Tag.increment_counter(:posts_count, self.tag.id)
end
end
def decrement_tag_counter_cache
if self.post.status == "Published" && self.post.published_at.nil?
Tag.decrement_counter(:posts_count, self.tag.id)
end
end
出于某种原因,现在计数器没有增加或减少。我尝试删除代码,发现问题出在这部分:self.post.published_at.nil?
.
我不太确定发生了什么事。我很确定published_at
就是nil
在那一刻。可能是什么问题呢?