counter_cache的关联表

时间:2016-07-12 17:30:40

标签: ruby-on-rails

使用Rails 4.我有以下内容:

class List < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :lists
  has_one :profile
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

我在lists_count表中有Profile,我想将它用作列表计数器缓存。我没有把它放在用户中,因为我的用户模型仅用于身份验证。我不想在身份验证之外添加任何不相关的列。

如何在每次创建列表时都这样做,Profile.lists_count获得+1?

1 个答案:

答案 0 :(得分:0)

我会在List模型中添加'after_create'方法:

 class List < ActiveRecord::Base
   after_create :add_to_list_count

#There are nicer ways to do this but this will get you going
   def add_to_list_count
     self.user.profile.lists_count = self.user.profile.lists_count + 1
     self.user.profile.lists_count.save
   end
 end