Count cache for model with many-to-many association

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

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 (model for the connection table):

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

I want to create :counter_cache , which keeps track of how many posts the tag has.

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

EDIT:

I have done this before:

comment.rb:

 belongs_to :post, :counter_cache => true 

But now that there is no belongs_to in the post.rb file. I'm a little confused.

+4
source share
2 answers

There seems to be no easy way to do this. If you look at this previous post. This seems to happen quite often, and, unfortunately, the rails do not have an easy way to accomplish this task. What you need to do is write code like this.

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

A (tag) has many C (messages) through B (tag)

 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.BAid ) end def decrement_A_counter_cache A.decrement_counter( 'c_count', self.BAid ) end end 
+1
source

tagging.rb (model for the connection table):

 class Tagging < ActiveRecord::Base belongs_to :post, counter_cache: :tags_count belongs_to :tag, counter_cache: :posts_count end 

add posts_count integer migration column in tags add tags_count integer column migration in messages

+7
source

Source: https://habr.com/ru/post/1400136/


All Articles