I have a weird case in my rails development that I’m not able to manage properly.
Basically, I have three objects: Domain, Project and Person ; a domain is a group of persons and projects. Domains can have several projects and projects can have several people however a project can only be in one domain and people can only work for projects in one domain.
I have represented it as following:
class Domain < ActiveRecord::Base
has_many :projects
class Project < ActiveRecord::Base
belongs_to :domain
has_and_belongs_to_many :persons
class Person < ActiveRecord::Base
belongs_to :domain
has_and_belongs_to_many :projects
I don’t know how to validate that all the projects added to a person belongs to the same domain. I have created a method for validating persons however it is still possible to add projects in other domains, the person saved in database will just not be valid.
Do you see a clean solution to this problem?
So, basically, you want to validate that a person takes projects only from one domain. I suppose this domain should be defined, meaning a person should have a
domain_idcolumn.You also have a many-to-many association, and, since the association needs some validations, you should have also a join model (instead of just a table without a model). I called it
Work. So, I have this:Now, to the
Workmodel you just addThis worked for me. Is this what you wanted?