使用计数器缓存来限制最大关系数

时间:2011-04-27 17:26:01

标签: ruby-on-rails-3

我试图阻止我的用户拥有超过5页。我的网页模型如下所示:

class Page < ActiveRecord::Base
  belongs_to :user, :counter_cache => true
  has_friendly_id :name, :use_slug => true, :strip_non_ascii => true
  validates_uniqueness_of :name, :case_sensitive => false
  validates_presence_of :name
end

我在数据库中添加了一个正在递增和递减的列。

我只是不知道我现在应该把什么放在我的控制器中以抛出错误并阻止它们添加太多。

再次感谢

- 更新 -

这就是我的用户模型现在的样子:

class User < ActiveRecord::Base
  has_many :pages, :dependent => :destroy, :before_add => :enforce_page_limit
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  validates_presence_of :name
  validates_uniqueness_of :name, :email, :case_sensitive => false

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :name, :email, :password, :password_confirmation, :remember_me
  has_friendly_id :name, :use_slug => true, :strip_non_ascii => true

  private

    def enforce_page_limit
      if self.pages_count >= 1
        self.errors.add_to_base "Page limit reached, can't add another page"
        raise "User page limit reaching, preventing page from being added"
      end
    end  
end

1 个答案:

答案 0 :(得分:1)

您可以在User-Pages关系的User侧使用:before_add回调。查看此页面的关联回调部分:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

您需要编写回调以检查是否已有5个与该用户相关的页面,如果有,则引发异常以阻止该页面与该用户相关。

<强>更新

以下是如何设置before_add回调的示例。

在您的用户模型中:

class User < ActiveRecord::Base

  has_many :pages, :before_add => :enforce_page_limit

  private

  def enforce_page_limit
    if self.pages.count >= 5
      self.errors.add_to_base "Page limit reached, can't add another page"
      raise "User page limit reaching, preventing page from being added"
    end
  end 

end