Re: validating associated model for has_many

Jodi Showers
Thu, 05 Jun 2008 18:17:44 -0000

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

>
> 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?

use User.find instead of the association

Jodi

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org