I’m trying to block my users from having more than 5 pages. My pages model looks like this:
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
And I’ve added a column in the db which is incrementing and decrementing fine.
I just don’t know what I should put in my controller now to thrown an error and stop them from adding too many.
Thanks again
— Update —
This is what my user model now looks like:
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
You can use a
:before_addcallback on the User side of the User-Pages relationship. Check out the Association callbacks section of this page: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.htmlYou’ll want to write the callback to check to see if there already are 5 pages related to the user, and if there is, raise an exception to block the Page from being related to the User.
UPDATE
Here’s an example of how you would set up the before_add callback.
In your User model: