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"):

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_atnilています。何が問題なのですか?

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 に答える