2014-11-21 30 views

回答

2

出於您的目的,我認爲您應該在AR關聯中使用像:counter_cache這樣的屬性。例如:

class Comment < ActiveRecord::Base 
    # cached value will stored into the comments_count column at posts table 
    belongs_to :post, counter_cache: true 
end 

class Post < ActiveRecord::Base 
    has_many :comments 
end 

Rails會在你不注意的情況下做很多工作。

對於上面提到的兩種方法(increcement_counterincresement),它們用於不同的目的。 increcement_countercounter_cache的魔術。 incresement僅用於增加表中的某個整數值。

+0

很酷,我假設'counter_cache'列的類型是'integer'? – Numbers 2014-11-21 15:46:55

+0

@數字當然 – achempion 2014-11-21 15:52:55

0

實例#increment_counter:更多的空中接力,並運行#update_all(快速,無驗證)。

相關問題