简体   繁体   中英

Multiple users to a task in Ruby on Rails

I'm making a project manager app in Ruby on Rails, and I have many 'tasks' (like issues on GitHub) that can have many 'users' assigned to them. For example, John Smith and Jane Doe could be working on Task 23. Kind of like how issues on GitHub can have multiple labels, but with users instead of labels.

I'm brand new to Ruby on Rails and I have no idea how to create the 'tasks' model so that it can reference multiple users. I also have no idea how to phrase this question, and I have tried Googling it but to no avail - sorry if this is a duplicate.

It sounds like in your app that your users can have many tasks and your tasks can have many users. In which case there are two options

  1. has_and_belongs_to_many configuration
  2. a full model that joins these two models together

In both cases, there will be a table that joins them, however, it depends on whether you need the functionality of a model between the two or not.

My suggestion is to start with #1 and you'll need to read up on associations to implement either option.

Example:

Assuming you have both a Users model or Tasks model you would create your has_and_belongs_to_many (HABTM) relationship as such:

$ rails g migration CreateUsersTasksJoinTable

This produces a migration file with a name similar to below. Update that file accordingly:

# db/migrate/201806XXXXXXXX_create_users_tasks_join_table.rb
class CreateUsersTasksJoinTable < ActiveRecord::Migration[5.1]
  def change
    create_join_table :users, :tasks
  end
end

Once you create the join table, then you need to update your User and Task models as such:

# app/models/user.rb
class User < ApplicationRecord
  has_and_belongs_to_many :tasks
end

# app/models/task.rb
class Task < ApplicationRecord
  has_and_belongs_to_many :user
end

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