2014-11-21 67 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(快速,无验证)。

相关问题