Forum: Ruby on Rails Validating that a foreign key is present and ok

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Eea3feaacbe44706164289d068d94828?d=identicon&s=25 Peter Michaux (Guest)
on 2006-03-01 21:50
(Received via mailing list)
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
C64e63b70be7dfed8b0742540b8b27e5?d=identicon&s=25 Mark Reginald James (Guest)
on 2006-03-01 23:50
(Received via mailing list)
Peter Michaux wrote:
>   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.
Eea3feaacbe44706164289d068d94828?d=identicon&s=25 Peter Michaux (Guest)
on 2006-03-02 00:05
(Received via mailing list)
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?
This topic is locked and can not be replied to.