Reputation: 353
I apologize for a beginner question, but I'm trying to wrap my head around ActiveRecord associations for the project I'm trying to start.
I'm beginning to expand my knowledge in Rails and I'm a bit confused with the available ActiveRecord associations, that is which one should I pick and how to structure the models.
This is the general concept:
What I'm looking is the best way to create the models for Company, Departments and Employees, so I can assign Employees to the correct Company and Department.
If you could point me to the right direction, book or tutorial/article to ease up these database table joins in my head and pick the right route for the project!
Any help is appreciated!
Upvotes: 0
Views: 86
Reputation: 781
Seems straight forward.
Your Company model should show the following:
has_many :departments
has_many :employees
One could argue you could change the employees to a "has_many :employees, through: :departments". I don't suspect it matters too greatly.
Your Department model should have:
belongs_to :company
has_many :employees
Your Employee model should have:
belongs_to :company
belongs_to :department
You don't technically need the company line if you use the through departments for that relationship. But if you do this you can then run things like:
Employee.first.company Employee.first.department
Department.first.business Department.first.employees.first (notice this is plural as it's has_many)
Company.first.employees.first (will work if you have a through or if you assign it directly) Company.first.departments.first
A "belongs_to" relationship means the model declaring it holds a foreign key for the model it belongs to. So, Department belongs_to Company. Thus, :company_id is created inside Department when you type, say, rails generate model Department company:references....etc.
In the example above, your Employee will have a :department_id and a :company_id, though, again, you may skip the company one and just declare it as a through and you will look up your employees through the departments they are in.
You could, in theory, also use a has_one instead of a belongs_to for employee. But I find those harder to work with.
Upvotes: 1