简体   繁体   中英

Rails activerecord associations

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:

  • You would first define a Company - that is the first part of the tree
  • Secondly, you need to define the Departments. They should belong to the Company in question, and have a simple name and description.
  • And finally - Employees - each employee can be in one Department and fall under one Company.

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM