Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you call <code>account.users.size</code> instead of <code>account.users.count</code> it will also include users which have been built but not saved to the database.</p> <p><strong>HOWEVER</strong> this will not fully solve your problem. When you call <code>account</code> in a user it is not returning the same account instance that <code>@account</code> is pointing to so it does not know about the new users. I believe this will be "fixed" in Rails 3, but in the meantime I can think of a couple solutions.</p> <p>If you are saving the account the same time you are adding users (which I assume so since you are calling <code>update_attributes</code>) then the validation can go in there.</p> <pre><code># in account.rb def validate_max_users_have_not_been_reached errors.add_to_base("You cannot have more than #{maximum_amount_of_users} users on this account.") unless users.size &lt; maximum_amount_of_users end </code></pre> <p>I'm not sure how you are saving the associated models, but if account validation fails they should not be saved.</p> <p>The other solution is to reset the <code>user.account</code> instance to self when updating user attributes. You could do this in the users_attributes setter method.</p> <pre><code># in account.rb def users_attributes=(attributes) #... user.account = self #... end </code></pre> <p>This way user's account will point to the same account instance so <code>account.users.size</code> should return the amount. In this case you would keep the validations in the user model.</p> <p>It's a tricky problem but hopefully this gave you some ideas on how to solve it.</p>
    singulars
    1. This table or related slice is empty.
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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