简体   繁体   中英

Ruby on Rails ActiveRecord task belongs to company & has_many users

I'm new to Ruby on Rails and was wonder if this is a good setup, or if there is a better configuration.

Background: The system will be used to assign tasks to users, track the assignor, and allow multiple people to be assigned the task.

Create a company model, user model, task model, and a user_tasks model.
Company Class
has_many :users
has_many :tasks

User Class
belongs_to :company
has_many :user_tasks
has_many :tasks, through: :user_tasks

Task Class
belongs_to :company
has_many :user_tasks
has_many :users, through: :user_tasks

UserTasks Class
belongs_to :user
belongs_to :task
*Tracks assignor with boolean

I think this is perfect. There is one big advantage of having a has_many (model1), through: (model2) association when compared to has_and_belongs_to_many association in that you can access the join model ( UserTasks your case) through the ActiveRecord query interface ( UserTask.where() or UserTask.find_by(user_id: 1) and so forth). Querying the join table directly can sometimes shorten your queries. If you use the has_and_belongs_to_many association you will have a database table that you cannot directly access in Rails without resorting to SQL.

You probably don't need the UserTasks class if it is just a habtm table. So just create a migration for that table, but skip adding the model. Then in User , do has_and_belongs_to_many :tasks and in Task do has_and_belongs_to_many :users

The other thing that I see is that company is set for both tasks and users. You might have business rules to why this has to be, but if not, you might just be able to say Company -> has_many :tasks, through: :users

I favor :has_many, :through over has_many_and_belongs_to_many or HABTM. For example, I can be assigned to a Task twice, one as a programmer and another time as a designer. So I need some kind of "JobDescription" column on the UserTask column, and I'd need two rows of the UserTask table to represent me being a programmer on a task, and another to represent me being a designer on a task.

You want to write software that is easier to change, even though HABTM is shorter, you might change the software in the future, like in the case of a person doing two subtasks in the same task. Remember that a row in a database is a piece of data, or "a thing", if that makes sense. At the very least, you get timestamps.

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