2014-04-18 23 views
0

我讀過關於計數器緩存的關聯。計數器緩存的條件不關聯

有沒有一種方法可以輕鬆地實現(通過一個寶石,將做繁重的舉措)的計數器緩存的某些條件?例如:

通常反緩存將

class User 
    has_many :messages 

class Message 
    belongs_to :user, counter_cache: true 
然而

,可以說,我不想算多少消息,但是從統計中的全部信息的字符總數喬

所以可以說我有一個方法count_chars_from(user)從用戶返回字符的數量

我想在很多事情發生在系統(當喬將消息發送到幾個人來更新特定的列 - 所有的那些用戶需要更新,當喬編輯一個人的消息,等等)

這可以與觀察員我想,但我看到我自己很快創建醜陋的代碼。

有沒有辦法像上面那樣?

+0

不,你必須自己實現它,例如'before_save' – mdesantis

回答

0

目前,這裏沒有特別的方法/幫手。 Rails不支持條件計數器。

但是,您可以簡單地定義自己的。

class Message 
    belongs_to :user 
    after_create :inc_counters 
    after_destroy :dec_counters 

    private 
    def inc_counters 
    if user && your_conditions 
     user.increment(:conditional_counter) 
    end 
    end 

    def dec_counters 
    if user && your_conditions 
     user.decrement(:conditional_counter) 
    end 
    end 
end 

我建議看看counter_cache implementation。它看起來相當複雜,但簡單的實現在我的一個項目中運行得很好。
也考慮使用update_column不觸發在User模型上的驗證和回調。
並測試你代碼刪除父模型,如果它有dependent: :destroy關聯。