Hi,
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.
Am I doing something wrong? I am using rails release 0.13.1-1 on Ubuntu
Linux.
Thx,
Fraser
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.
Mark Reginald James wrote:> 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 :clubValidation now works. It doesn''t strike me as intuitive, perhaps we need validates_associated_and_exists :-) Thx, Fraser