Cross Model Validation

So I have this question:

Suppose I have these 3 models:

class Company < ActiveRecord::Base   has_many :departments   has_many :employees end

class Department < ActiveRecord::Base   has_many :employees   belongs_to :company end

class Employee < ActiveRecord::Base   belongs_to :company   belongs_to :department end

Furthermore, suppose the domain I am modeling requires that I support the existence of employees that do not belong to any department (otherwise I would declare that Company has_many :employees, :through => :departments instead).

As I am working with the Department model, I am thinking that it is conceivable that a mistake can be made in the code to allow an employee from a company to be incorrectly assigned to a department in another company. Hence, it might be a good idea to write some custom validation to ensure an employee and a department belong to the same company before they associated together.

Since associate a department and an employee together in one of two ways, I would need validation logic in both models. So I am thinking it would involve something like:

1. In the Department model

def validate   self.errors.add(:employees, "must all belong to same company") if self.employees.collect { |e| e.company_id }.uniq.length > 1 end

2 In the Employee model:

def validate   self.errors.add(:department, "must belong to the same company") if self.department && self.department != self.company end

However, having to write two separate methods to support a single business rule feels not so DRY or elegant. Is there a better way to go?

Thanks!

Well one way to finesse this might be to have a fictional/notional catch-all department for each company, like "company staff" which acts as a placeholder for employes not actually belonging to a 'real' department.