本文介绍了具有多对多关联的模型的计数器缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Post 和一个 Tag 模型,带有 many-to-many 关联:

I have a Post and a Tag model with a many-to-many association:

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

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

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

class Tagging < ActiveRecord::Base
  belongs_to :post  
  belongs_to :tag
end

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

I want to create a :counter_cache that tracks how many posts a tag has.

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

How can I accomplish that in this many-to-many association?

我以前这样做过:

comment.rb:

belongs_to :post, :counter_cache => true

但是现在 post.rb 文件中没有 belongs_to.我有点糊涂了.

But now that there isn't a belongs_to in the post.rb file. I'm a bit confused.

推荐答案

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

It seems like there is no real easy way to do this. If you look at this previous post. It seems like this comes up fairly often and sadly rails does not have an easy way to complete this task. What you will need to do is write some code like this.

虽然,我也建议将 has_and_belongs_to_many 关系视为这可能就是你在这里所拥有的.

Although, I would also suggest looking into has_and_belongs_to_many relationships as that might be what you have here.

A(Tag) 有很多 C(posts) 到 B(tagging)

A(Tag) has many C(posts) through B(tagging)

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

这篇关于具有多对多关联的模型的计数器缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 09:45