Peter Michaux
2006-Mar-01 20:49 UTC
[Rails] Validating that a foreign key is present and ok
How do I validate that a model object''s attribute is a valid foreign key? The problem is, I can''t check if the attribute is a valid foreign key if the attribute doesn''t even exist. For example, every employee must be in a department. In the following code, if an employee''s department_id is not present then Department.find_by_id(department_id) might cause problems, yes? class Employee < ActiveRecord::Base validates_presence_of :department_id def validate errors.add(:department_id) unless Department.find_by_id(department_id) end end department_id should be present, a positive integer, and a valid foreign key to the departments table. This is a common thing to want to validate. How do you do it? Thanks, Peter
Mark Reginald James
2006-Mar-01 22:49 UTC
[Rails] Re: Validating that a foreign key is present and ok
Peter Michaux wrote:> How do I validate that a model object''s attribute is a valid foreign > key? The problem is, I can''t check if the attribute is a valid foreign > key if the attribute doesn''t even exist. > > For example, every employee must be in a department. In the following > code, if an employee''s department_id is not present then > Department.find_by_id(department_id) might cause problems, yes? > > > class Employee < ActiveRecord::Base > validates_presence_of :department_id > def validate > errors.add(:department_id) unless Department.find_by_id(department_id) > end > end > > department_id should be present, a positive integer, and a valid > foreign key to the departments table. This is a common thing to want > to validate. How do you do it?All you need is "validates_presence_of :department". -- We develop, watch us RoR, in numbers too big to ignore.
Peter Michaux
2006-Mar-01 23:05 UTC
[Rails] Re: Validating that a foreign key is present and ok
On 3/1/06, Mark Reginald James <mrj@bigpond.net.au> wrote:> All you need is "validates_presence_of :department".Why? When is the validity of the foreign key checked? What error message does it add?