Skip to content

Instantly share code, notes, and snippets.

@kylefox
Last active February 7, 2018 21:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kylefox/1ef9af09a1cd5e7c196fdd3b887247ad to your computer and use it in GitHub Desktop.
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