0

我的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在那一刻。可能是什么问题呢?

4

1 回答 1

1

你怎么知道

post.status == "Published" && post.published_at is really nil?

?

post.published_at 可以只是空白。喜欢 ””

post.published_at.blank?

.blank 的例子?和 .nil?:

"".nil?
#=> false

nil.nil?
#=> true

nil.blank?
#=> true

"".blank?
#=> true

"  ".blank?
#=> true

"     ".blank?
#=> true   

[].blank?
#=> true

{}.blank?
#=> true
于 2012-12-29T04:03:39.613 回答