Re: validates_associated ... doesn''t

Mark Reginald James
Wed, 26 Oct 2005 18:33:02 -0000

Fraser Campbell wrote:

> I think I''m missing some fundamental information here so hopefully
> someone can help me.  I have a model Club which has many members,
> members of course belong to a Club.  I''d like to ensure that when
a
> members is saved (saved/created/updated) only valid club_id''s are
accepted.
>
> I have a Club model (simplified) like this:
>
>   class Club < ActiveRecord::Base
>     has_many :members
>   end
>
> I have a Member model (simplified) like this:
>
>   class Member < ActiveRecord::Base
>     belongs_to :club
>     validates_associated :club
>     validates_presence_of :club_id
>   end
>
> All other validations (not shown) and basic CRUD works as expected.
> However, when I insert a junk club_id it is accepted and saved in the
> database.

[What a wonderful example for the has_many/belongs_to syntax.]

With a junk club_id the value of member.club is nil because the
record can''t be found, and validates_associated treats this as
unassigned and hence valid.

Instead, replace both the above validate helpers with
       validates_presence_of :club


--
We develop, watch us RoR, in numbers too big to ignore.