# Validating associated model for has\_many

**URL:** <https://www.ruby-forum.com/t/validating-associated-model-for-has-many/139652>\
**Category:** Rails\
**Created:** [June 5, 2008, 8:14pm UTC](https://www.ruby-forum.com/t/validating-associated-model-for-has-many/139652 "2008-06-05T20:14:48Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![sw0rdfish](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/edb3f5/32.png) [@sw0rdfish](https://www.ruby-forum.com/u/sw0rdfish)\
**Post date:** [June 5, 2008, 8:14pm UTC](https://www.ruby-forum.com/t/validating-associated-model-for-has-many/139652/1 "2008-06-05T20:14:48Z")

</div>

Hi guys n’ gals.

Quick Q on this… it should be easy, but it’s not…

I’ve got users and members… and a Member has\_many Users. I want to  
have validation that ensures that the member has at least one user.

validates\_presence\_of :user doesn’t work because the user and member  
aren’t associated until after a save! is called ( the member\_id field  
of User stays nil ).

I tried using validates as follows:

validate :must\_have\_user

def must\_have\_user  
errors.add\_to\_base(“Must have at least one user”) unless  
self.users.count \> 0  
end

but member.users.count stays at 0, even though I used  
member.users.build to create the user.

Any ideas on how I can get this to validate? Rails obviously knows  
that the user and member are related… how can I confirm this?

Thanks!  
Randal

---

<div class="post-metadata">

**Author:** ![sw0rdfish](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/edb3f5/32.png) [@sw0rdfish](https://www.ruby-forum.com/u/sw0rdfish)\
**Post date:** [June 5, 2008, 8:18pm UTC](https://www.ruby-forum.com/t/validating-associated-model-for-has-many/139652/2 "2008-06-05T20:18:25Z")

</div>

On 5-Jun-08, at 2:14 PM, sw0rdfish wrote:

> of User stays nil ).  
> but member.users.count stays at 0, even though I used  
> member.users.build to create the user.
> 
> Any ideas on how I can get this to validate? Rails obviously knows  
> that the user and member are related… how can I confirm this?

use User.find instead of the association

Jodi

---

<div class="post-metadata">

**Author:** ![sw0rdfish](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/edb3f5/32.png) [@sw0rdfish](https://www.ruby-forum.com/u/sw0rdfish)\
**Post date:** [June 5, 2008, 8:26pm UTC](https://www.ruby-forum.com/t/validating-associated-model-for-has-many/139652/3 "2008-06-05T20:26:04Z")

</div>

and I’m a goof…

just remembered that members.users.count would query the DB, which is  
0… however if you use members.users.size, it’ll query the object in  
memory 🙂

SO my validate method is…

def must\_have\_user  
errors.add\_to\_base(“Must have at least one user”) unless  
self.users.size \> 0  
end

and then it works 🙂

I’ll be happy to take any more advice on this though, thanks 🙂
