私の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"
):
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
何らかの理由で、現在、カウンターはインクリメントまたはデクリメントされていません。コードを削除してみたところ、問題はこの部分にあることがわかりself.post.published_at.nil?
ました。
何が起こっているのかよくわかりません。私はその瞬間にかなり確信published_at
しnil
ています。何が問題なのですか?