For the record, I ended up coding a validate method on the model like
so:
def validate
errors.add("", "Group #{self[''group_id'']} Not
Found") unless
Group.exists?(self["group_id"])
end
I like Ruby and Rails problems often distill down to neat one liners ...
-----Original Message-----
From: rails-bounces-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
[mailto:rails-bounces-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org] On
Behalf Of Neville
Burnell
Sent: Monday, 18 July 2005 1:27 PM
To: rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
Subject: [Rails] Validations and belongs_to: etc
Hi,
Say I have two models, User and Group whereby each User belongs to a
Group, like so:
class User < ActiveRecord::Base
belongs_to :Group
end
class Group < ActiveRecord::Base
has_many :Users
end
Whats "The Rails Way" TM to add a ''lookup''
validation to the User model
such that Rails will check that the group exists in the DB on saving ?
eg:
u = User.new
u[''group_id''] = group_id
u.save
I''ve looked at the ''validates_...'' helpers, but
couldn''t find what I was
looking for, ie, something like:
validate_exists :group
At the moment, the way forward seems to be something like:
u = User.new
u[''group_id''] = group_id
if u.group.nil?
# group_id not valid ... do something
end
u.save
But I''d rather code something that fits with the Rails
''validates_''
framework
Any comments welcome
Nev
_______________________________________________
Rails mailing list
Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
http://lists.rubyonrails.org/mailman/listinfo/rails