具有多对多关联的模型的计数器缓存

ale*_*nco 4 ruby-on-rails

我有一个带有关联的PostTag模型many-to-many:

post.rb:

class Post < ActiveRecord::Base
  attr_accessible :title, :content, :tag_names

  has_many :taggings, :dependent => :destroy
  has_many :tags, :through => :taggings

  attr_writer :tag_names
  after_save :assign_tags

  def tag_names
    @tag_names || tags.map(&:name).join(" ")
  end

  private

  def assign_tags
    ntags = []
    @tag_names.to_s.split(" ").each do |name|
      ntags << Tag.find_or_create_by_name(name)
    end
    self.tags = ntags
  end
end
Run Code Online (Sandbox Code Playgroud)

tag.rb:

class Tag < ActiveRecord::Base
  has_many :taggings, :dependent => :destroy  
  has_many :posts, :through => :taggings
  has_many :subscriptions
  has_many :subscribed_users, :source => :user, :through => :subscriptions
end
Run Code Online (Sandbox Code Playgroud)

tagging.rb(连接表的模型):

class Tagging < ActiveRecord::Base
  belongs_to :post  
  belongs_to :tag
end
Run Code Online (Sandbox Code Playgroud)

我想创建一个:counter_cache跟踪标签有多少帖子的内容.

如何在这种多对多关联中实现这一目标?

编辑:

我以前这样做过:

comment.rb:

belongs_to :post, :counter_cache => true
Run Code Online (Sandbox Code Playgroud)

但现在还没有一个belongs_topost.rb文件.我有点困惑.

zet*_*ova 7

tagging.rb(连接表的模型):

class Tagging < ActiveRecord::Base
  belongs_to :post,  counter_cache: :tags_count
  belongs_to :tag,  counter_cache: :posts_count
end
Run Code Online (Sandbox Code Playgroud)

在列中添加列迁移posts_count整数在帖子中添加列迁移tags_count整数


Jus*_*ick 2

似乎没有真正简单的方法可以做到这一点。如果你看一下之前的帖子。这种情况似乎经常出现,遗憾的是 Rails 没有一种简单的方法来完成这项任务。您需要做的就是编写一些像这样的代码。

尽管如此,我也建议研究has_and_belongs_to_many关系,因为这可能就是你在这里所拥有的。

A(标签)通过 B(标签)有很多 C(帖子)

class C < ActiveRecord::Base
    belongs_to :B

    after_create :increment_A_counter_cache
    after_destroy :decrement_A_counter_cache

    private

    def increment_A_counter_cache
        A.increment_counter( 'c_count', self.B.A.id )
    end

    def decrement_A_counter_cache
        A.decrement_counter( 'c_count', self.B.A.id )
    end
end
Run Code Online (Sandbox Code Playgroud)