I have an account model and a user model:
class Account < ActiveRecord::Base has_many :users end class User < ActiveRecord::Base belongs_to :account end
Users belong to the account, and the account has a maximum user size (for each account - different). But how can I confirm that this maximum was not reached when adding new users to the account?
First I tried to add user validation:
class User < ActiveRecord::Base belongs_to :account validate :validate_max_users_have_not_been_reached def validate_max_users_have_not_been_reached return unless account_id_changed? # nothing to validate errors.add_to_base("can not be added to this account since its user maximum have been reached") unless account.users.count < account.maximum_amount_of_users end end
But this only works if I add one user at a time.
If I add multiple users via @account.update_attributes(:users_attributes => ...) , it just goes straight ahead, even if there is only room for another user.
Update:
Just to clarify: the current verification method confirms that account.users.count less than account.maximum_amount_of_users . For example, let's say that account.users.count is 9 and account.maximum_amount_of_users is 10, then the check will pass because 9 <10.
The problem is that the counter returned from account.users.count will not increase until all users are written to the database. This means that adding multiple users at the same time will be tested, as the user counter will be the same until all of them are verified.
So, as yggggy points out, should I add confirmation to my account model? And how should this be done?
validation ruby-on-rails activerecord
Thomas watson
source share