I am struggling implementing this ER diagram in rails, i wonder if it is even right.
So basically what i am trying to do is :
-a person has many roles
-a role is an organization +a position
-an position/organization has many roles
-from a position/organization i can retrieve all the roles
-from a role i can retrieve the people or a person
It looks to me that âroleâ is essentially an extended linker table for organizations, roles and people.
class Person < ActiveRecord::Base
has_many :roles
has_many :organizations, through: :roles
has_many :positions, through: roles
end
class Role < ActiveRecord::Base
belongs_to :person
belongs_to :organization
belongs_to :position
end
class Organization < ActiveRecord::Base
has_many :roles
has_many :people, through: roles
end
class Position < ActiveRecord::Base
has_many :roles
has_many :people, through: roles
end
You can tell that you donât need additional tables because all the foreign keys youâd need to relate everything are tracked in the âroleâ class, and it seems like it wraps up all the use cases youâve outlined.
Iâve found that a lot of many-to-many relations benefit from âhas_many :throughâ, because you frequently want to track metadata on the relation, or (in your case) bring together more than just two models.
this is awesome, now how can i make the model Role accept something like:
Role.create(:person=>Person.first âŚ) instead of Role.create(:person_id=>Person.first.id âŚ)