Note that there are some explanatory texts on larger screens.

plurals
  1. POValidate max amount af associated objects
    primarykey
    data
    text
    <p>I have an Account model and a User model:</p> <pre><code>class Account &lt; ActiveRecord::Base has_many :users end class User &lt; ActiveRecord::Base belongs_to :account end</code></pre> <p>Users belong to an account and an account have a user maximum (different for each account). But how do I validate that this maximum have not been reached when adding new users to an account?</p> <p>First I tried to add a validation on the user:</p> <pre><code>class User &lt; 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 &lt; account.maximum_amount_of_users end end</code></pre> <p>But this only works if I'm adding one user at a time.</p> <p>If I add multiple users via <code>@account.update_attributes(:users_attributes =&gt; ...)</code> it just goes directly through even if there is only room for one more user.</p> <p><strong>Update:</strong></p> <p>Just to clarify: The current validation method validates that <code>account.users.count</code> is less than <code>account.maximum_amount_of_users</code>. So say for instance that <code>account.users.count</code> is 9 and <code>account.maximum_amount_of_users</code> is 10, then the validation will pass because 9 &lt; 10.</p> <p>The problem is that the count returned from <code>account.users.count</code> will not increase until all the users have been written to the database. This means adding multiple users at the same time will pass validations since the user count will be the same until after they are all validated.</p> <p>So as <em>askegg</em> points out, should I add validation to the Account model as well? And how should that be done?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload