3

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

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

所以真的,似乎我应该使用一个:through关联而不是两个单独的关联来完成这个。

但是,我找不到任何建议混合使用 has_many :through 和 has_one :through 关联的参考,仅适用于一对一和多对多,而不适用于一对多。

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

像上面那样可取,还是我应该手动处理计数器缓存?

4

2 回答 2

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 时遇到了麻烦。上面的方法应该有效。

于 2012-06-09T17:33:36.387 回答
-1

所以普通的计数器缓存似乎工作得很好,混合关系类型也是如此

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
于 2012-06-10T15:39:16.553 回答