Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
When two models (Project, Employee) belong to a parent (Company) and are joined through a join model (ProjectEmployee), what's the best way to ensure that the two instances being joined belong to the same parent? Ex: how do you ensure the joined project and employee belong to the same company?
class Company < ApplicationRecord
has_many :employees
has_many :projects
end
class Project < ApplicationRecord
belongs_to :company
has_many :project_employees
has_many :employees, through: :project_employees
end
class Employee < ApplicationRecord
belongs_to :company
has_many :project_employees
has_many :projects, through: :project_employees
end
class ProjectEmployee < ApplicationRecord
belongs_to :project
belongs_to :employee
# There has to be a better way! 👇
validate :project_and_employee_belong_to_same_company
def project_and_employee_belong_to_same_company
if project.company != employee.company
errors.add(:base, 'Project and employee do not belong to same company.')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.