如何在这种多对多关联中使用counter_cache?

时间:2012-12-27 12:01:36

标签: ruby-on-rails many-to-many

我在many-to-manyPost模型之间建立了Tag关联:

post.rb:

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

tag.rb:

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

标记:

attr_accessible :tag_id, :post_id

belongs_to :post
belongs_to :tag

我希望有一个页面,其中列出了所有标签以及每个标签有多少个帖子。

所以我在标记中添加了posts_count列:

  create_table "tags", :force => true do |t|
    t.string   "name"
    t.datetime "created_at",                 :null => false
    t.datetime "updated_at",                 :null => false
    t.integer  "posts_count", :default => 0, :null => false
  end

我之前使用过计数器缓存:

reply.rb:

 belongs_to :post, :counter_cache => true

但我不确定如何使用此many-to-many关联。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

对标签使用common:counter_cache选项。尽管它对Taggings对象进行了计数,而且这些对象属于(只有一个)帖子,但这正是你要找的。

# tagging:

attr_accessible :tag_id, :post_id

belongs_to :post
belongs_to :tag, :counter_cache => :posts_count

validates_uniqueness_of :tag_id, :scope => :post_id

Validator将阻止为相同的帖子创建多个相同的标签,因此您可以避免重复记录。

相关问题