简体   繁体   English

Ruby on Rails中的一个任务有多个用户

[英]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. 我正在Ruby on Rails中创建一个项目经理应用程序,并且我有很多“任务”(例如GitHub上的问题),可以为他们分配许多“用户”。 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. 例如,John Smith和Jane Doe可能正在研究Task23。有点像GitHub上的问题可以有多个标签,但使用用户而不是标签。

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. 我是Ruby on Rails的新手,我不知道如何创建“任务”模型,以便它可以引用多个用户。 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. 我也不知道该如何表达这个问题,我已经尝试了Google搜索,但无济于事-如果这是重复的,对不起。

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 has_and_belongs_to_many配置
  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. 我的建议是从#1开始,您需要阅读关联才能实现这两个选项。

Example: 例:

Assuming you have both a Users model or Tasks model you would create your has_and_belongs_to_many (HABTM) relationship as such: 假设您同时具有用户模型或任务模型,则可以这样创建has_and_belongs_to_manyhas_and_belongs_to_many )关系:

$ 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: 创建联接表后,您需要像这样更新UserTask模型:

# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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