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

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

概述我有一个具有多对多关联的Post和Tag模型: post.rb: class Post < ActiveRecord::Base attr_accessible :title, :content, :tag_names has_many :taggings, :dependent => :destroy has_many :tags, :through => :taggings 我有一个具有多对多关联的Post和Tag模型:

post.rb:

class Post < ActiveRecord::Base  attr_accessible :Title,:content,:tag_@R_419_6889@s  has_many :taggings,:dependent => :destroy  has_many :Tags,:through => :taggings  attr_writer :tag_@R_419_6889@s  after_save :assign_Tags  def tag_@R_419_6889@s    @tag_@R_419_6889@s || Tags.map(&:@R_419_6889@).join(" ")  end  private  def assign_Tags    nTags = []    @tag_@[email protected]_s.split(" ").each do |@R_419_6889@|      nTags << Tag.find_or_create_by_@R_419_6889@(@R_419_6889@)    end    self.Tags = nTags  endend

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 => :subscriptionsend

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

class Tagging < ActiveRecord::Base  belongs_to :post    belongs_to :tagend

我想创建一个: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 )    endend
总结

以上是内存溢出为你收集整理的ruby-on-rails – 具有多对多关联的模型的计数器缓存全部内容,希望文章能够帮你解决ruby-on-rails – 具有多对多关联的模型的计数器缓存所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1286699.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存