2011-04-27 43 views
2

我試圖阻止我的用戶擁有超過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 

而且我在db中增加了一個列,這個列正在遞增和遞減。

我只是不知道我應該把我的控制器現在拋出一個錯誤,並阻止他們添加太多。

再次感謝

- 更新 -

這是我的用戶模型現在看起來像:

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

您可以在用戶 - 用戶側使用:before_add回調頁面關係。看看這個頁面的協會回調部分:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

你想要寫的回調來檢查,看看是否有已經是關係到用戶5頁,如果有,引發異常阻止該頁面與用戶相關。

UPDATE

這裏,你會如何設置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 
+0

感謝您的回答,我得到的概念,但是這是我的出路的認識領域。我只是一個新手!你碰巧知道我可以看的任何教程 - 看看你發送的鏈接,但看不到任何足夠清晰的東西。再次感謝 – 2011-04-27 17:56:57

+0

我用一些示例代碼更新了答案,這是否有幫助? – ctcherry 2011-04-27 18:01:16

+0

太棒了 - 再次感謝。我只是在嘗試自己的解決方案而沒有成功。已經把你的代碼放在我的用戶模型中,但它似乎並不適用。沒有錯誤顯示,我可以創建一個新頁面,即使我已將計數減少到1.我將代碼放在第一個編輯中... – 2011-04-27 18:13:06