2012-12-29 19 views
0

我有一個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設置負值。那可能嗎?

(這不應該作爲工作驗證,而是作爲默認行爲,因爲我不希望錯誤顯示出來做的。)

回答

1

你可以把驗證上POSTS_COUNT如下

validates :posts_count, :numericality => { :greater_than_or_equal_to => 0 } 

或者你也可以做這樣的事情

before_save :set_posts_count 

def set_posts_count 
    posts_count = 0 if posts_count < 0 
end 
+0

所以,如果'decrement_count'想讓'posts_count' -1它會自動變成0沒有任何錯誤(順便說一下,應該不會是'greater_or_equal_than => 0'? – alexchenco

+0

同意應該GREATER_THAN_OR_EQUAL_TO => 0,不能肯定有關設置默認值,但你可以做的就是讓一個方法調用和設置的默認值設置爲0,如果有上POSTS_COUNT –

+1

在這裏你去另一個選擇驗證錯誤 –

0

可能會出現問題,因爲這個方法,只要我還記得,那並不初始化模型實例,所以它發出了一個直接的SQL查詢升IKE這一個:

UPDATE "Tags" SET "posts_counter" = COALESCE("posts_counter", 0) - 1 WHERE "Tags"."id" = 5 

如果是這樣,我不知道如何解決這個問題,也許你可以用一個鎖初始化的模型實例,然後遞減計數器,但鎖有它的缺點

0

你可以做這樣的事情

[posts_count, 0].max 
相關問題