我有一個posts_count
列充當計數器緩存職位數的標籤型號標籤有:如何使列0的最小值(或阻止decrement_counter設置負值)?
schema.rb:
t.integer "posts_count", :default => 0, :null => false
tagging.rb:
def decrement_tag_counter_cache
Tag.decrement_counter(:posts_count, self.tag.id) if !post.published? || post.decrement_tag_counters?
end
post.rb:
after_save :increment_decrement_tag_counters # covers :save, :create, :update methods
def increment_tag_counters? # if status changes and the previous status wasn't "Published"
status_changed? && changed_attributes["status"] != "Published"
end
def decrement_tag_counters? # if status changes and the previous status was "Published"
status_changed? && changed_attributes["status"] == "Published"
end
def increment_decrement_tag_counters
if published? && increment_tag_counters?
taggings.each { |tagging| tagging.increment_tag_counter_cache }
elsif decrement_tag_counters?
taggings.each { |tagging| tagging.decrement_tag_counter_cache }
end
end
現在的問題是,有時,decrement_tag_counter_cache
方法會使posts_count
變爲負值(例如, -1)。
有沒有告訴Rails的任何方式:使posts_count
0最小值?所以如果當前值爲0並且計數器遞減,posts_count
仍然會保持0?我能做的另一件事是阻止decrement_counter
設置負值。那可能嗎?
(這不應該作爲工作驗證,而是作爲默認行爲,因爲我不希望錯誤顯示出來做的。)
所以,如果'decrement_count'想讓'posts_count' -1它會自動變成0沒有任何錯誤(順便說一下,應該不會是'greater_or_equal_than => 0'? – alexchenco
同意應該GREATER_THAN_OR_EQUAL_TO => 0,不能肯定有關設置默認值,但你可以做的就是讓一個方法調用和設置的默認值設置爲0,如果有上POSTS_COUNT –
在這裏你去另一個選擇驗證錯誤 –