My Post model has the following columns:
t.datetime "published_at"
t.string "status"
published_at Should only be defined once (the first time the post.status equals "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
Now, I added a posts_count column to the Tag model:
t.integer "posts_count", :default => 0, :null => false
The counter should only increment and decrement if the post.status equals "Published" (Shouldn’t increment is post.status equals "Draft"):
taggings.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
For some reason, the right now the counter is not being incremented or decremented. I tried removing code and discovered that the problem is this part: self.post.published_at.nil?.
I’m not very sure what’s going on. I’m pretty sure published_at is nil at that moment. What could be the problem?
How do you know that
?
post.published_at can be just blank. like “”
Examples of .blank? and .nil?: