Last active
February 7, 2018 21:53
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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