用于关联关联的计数器缓存

时间:2012-06-09 17:07:38

标签: ruby-on-rails activerecord one-to-many counter-cache

我有一个论坛模型,有很多讨论。每个讨论都有很多帖子。讨论或多或少只是一个帖子对象的集合。

现在我想在论坛中提供一个counter_cache,用于论坛讨论中包含的帖子。

实际上,似乎我应该使用:through关联而不是两个单独的关联来实现此目的。

但是我找不到任何建议混合has_many:through和has_one:通过关联,只是一对一和多对多,而不是一对多。

class Forum < ActiveRecord::Base
  has_many :discussions
  has_many :posts, :through => :discussions
end

class Post < ActiveRecord::Base
  belongs_to :discussion
  has_one :forum, :through => discussion
end

class Discussion < ActiveRecord::Base
  has_many :posts
  belongs_to :forum
end

类似于上面的建议,还是我应该手动处理计数器缓存?

2 个答案:

答案 0 :(得分:2)

这样的事情应该有效。

class Forum < ActiveRecord::Base
  has_many :discussions
  has_many :posts, :through => :discussions
end

class Post < ActiveRecord::Base
  belongs_to :discussion, counter_cache: true
  has_one :forum, :through => discussion

  after_create :increment_forum_counter_cache

  private

  def increment_forum_counter_cache
     Forum.increment_counter( 'discussions_count', self.discussion.forum.id )
  end
end

class Discussion < ActiveRecord::Base
  has_many :posts
  belongs_to :forum

end

我似乎记得以前通过has_one关系设置counter_cache时遇到问题。上面的方法应该有效。

答案 1 :(得分:0)

因此正常的计数器缓存似乎正常工作,混合关系类型

也是如此
class Post < ActiveRecord::Base
  belongs_to :user
  belongs_to :discussion
  has_one :forum, :through => :discussion,
            :counter_cache => :posts_counter
end
class Forum < ActiveRecord::Base
  has_many :discussions
  has_many :posts, :through => :discussions
end

class Discussion < ActiveRecord::Base
  has_many :posts
  belongs_to :forum
  belongs_to :user
end
相关问题