validating associated model for has_many

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

use User.find instead of the association

Jodi

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 :slight_smile:

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 :slight_smile:

I'll be happy to take any more advice on this though, thanks :slight_smile: