加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 具有多对多关联的模型的计数器缓存

发布时间:2020-12-17 02:54:01 所属栏目:百科 来源:网络整理
导读:我有一个具有多对多关联的Post和Tag模型: 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 :assi
我有一个具有多对多关联的Post和Tag模型:

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来跟踪标签有多少帖子.

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

编辑:

我以前这样做过:

comment.rb:

belongs_to :post,:counter_cache => true

但现在post.rb文件中没有belongs_to.我有点困惑.

解决方法

似乎没有真正简单的方法来做到这一点. If you look at this previous post.看起来这种情况经常发生,而且很遗憾,rails没有简单的方法来完成这项任务.你需要做的是写一些像这样的代码.

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

A(Tag)有很多C(帖子)到B(标记)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读