callback - How do I restrict the number of clients that a user can add in Rails 3? -
basically want happen is, each user ('designer') can add number of clients restricted plan. if plan allows 1 client, that's can do.
my user model looks this:
class user < activerecord::base devise :database_authenticatable, :confirmable, :registerable, :timeoutable, :recoverable, :rememberable, :trackable, :validatable, :invitable has_many :clients, :through => :client_ownerships, :order => 'created_at desc' {edited brevity} end
the client model looks this:
class client < activerecord::base before_save :number_of_clients belongs_to :user has_many :projects, :order => 'created_at desc', :dependent => :destroy has_one :ownership, :dependent => :destroy has_one :designer, :through => :ownership validates :name, :presence => true, :length => {:minimum => 1, :maximum => 128} def number_of_clients authorization.current_user.clients.count < authorization.current_user.plan.num_of_clients end end
the plan model looks this:
# == schema information # schema version: 20110214082231 # # table name: plans # # id :integer not null, primary key # name :string(255) # storage :float # num_of_projects :integer # num_of_clients :integer # cached_slug :string(255) # created_at :datetime # updated_at :datetime # price :integer # class plan < activerecord::base has_many :users has_friendly_id :name, :use_slug => true end
rather having number_of_clients
method called before_save
callback, use validation callback instead:
# app/models/client.rb validate :is_within_plan_limits def is_within_plan_limits errors.add(:client, 'you cannot add client') if user.max_clients? end # app/models/user.rb def max_clients? authorization.current_user.clients.count > authorization.current_user.plan.num_of_clients end # app/controllers/client_controller.rb def new redirect_to(some_path, :notice => 'time upgrade') , return if current_user.max_clients? end
see docs on here.
you can check number of clients in controller new action make sure user has free client slot, , direct them upgrade if not. validation enforce ui.
Comments
Post a Comment