使用:counter_cache有一些条件

时间:2011-06-01 06:51:33

标签: ruby-on-rails model associations counter-cache

我有以下型号:

class EntityTag < ActiveRecord::Base
  attr_protected :user_id, :post_id, :entity_id

  belongs_to :user
  belongs_to :post
  belongs_to :entity

  validates :user_id, :presence => true
  validates :entity_id, :presence => true
  validates :post_id, :presence => true

  validates_uniqueness_of :user_id, :scope => [:entity_id, :post_id]
end

Post模型中的杠杆作用如下:

class Post < ActiveRecord::Base
  ...
  has_many :entity_tags, :dependent => :destroy
  has_many :tags, :through => :entity_tags, :uniq => true,
    :source => :entity
  has_many :taggers, :through => :entity_tags, :uniq => true,
    :source => :user
  ...
end

我想保留两件事: 1)特定post_id的entity_tags数。这可以通过:EntityTag模型中的post:counter_cache来完成。 2)我还想基于特定post_id的唯一:entity_id值来跟踪UNIQUE EntityTags的数量。我该如何实现这一目标?我可以使用:counter_cache有某种约束吗?或者有一种完全不同的方法吗?

0 个答案:

没有答案