自动计算子表行数

示例

 

class Entry < ActiveRecord::Base
  has_many :entry_comments
end

class EntryComment < ActiveRecord::Base
  belongs_to :entry, :counter_cache => true
end

 

在主表(entries)中加一个名为子表(复数)_count(entry_comments_count)的字段,并设置默认值为0。此时,当调用EntryCommentsController中的create或者destroy方法时,entry_comments_count的值便会相应的加1或者减1。需要取出entry对应的entry_comment的数量时,可以直接取出对应的entry_comments_count的值,或者entry.entry_comments.size,这种情况只会统计加上:counter_cache => true后的数量。

下面看一个例子:

首先给entry1增加一条对应的entry_comment记录,给entry2增加两条对应的entry_comment记录,然后加上entry_comments_count以及:counter_cache => true,这时entry1以及entry2的entry_comments_count均为0,然后再给entry1增加一条对应的entry_comment记录,给entry2增加两条对应的entry_comment记录,此时entry1的entry_comments_count以及entry.entry_comments.size均为1,entry2的entry_comments_count以及entry.entry_comments.size均为2,如果需要统计entry对应的所有的entry_comment的数量,使用entry.entry_comments(:refresh).size即可,此时entry1的entry.entry_comments(:refresh).size为2,entry2的entry.entry_comments(:refresh).size为4。

你可能感兴趣的:(cache,ActiveRecord)