[英]ruby on rails — can two Models belong to each other?
My group is making a Project Management System for our course, and it's my job that when a user is logged in, that they see the projects they are part of, and also that the projects listed have a members list of current members of that project. 我的小组正在为我们的课程创建一个项目管理系统,这是我的工作,当用户登录时,他们可以看到他们所属的项目,并且列出的项目具有该项目当前成员的成员列表。 。
(Also will need an add/delete member function later) (稍后还将需要添加/删除成员函数)
My question is, since the rest of the group have already set it up so that Projects belong to Users, is it possible to have Users belong to Projects in order to set up this member list and do what I'm talking about? 我的问题是,由于该组的其余成员已经将其设置为项目属于用户,是否可以使用户属于项目才能设置此成员列表,我在说什么?
The relation you are describing is not one-to-one: 您描述的关系不是一对一的:
when a user is logged in, that they see the projects they are part of 当用户登录时,他们会看到他们所属的项目
This implies that a user can have several projects . 这意味着用户可以有多个项目 。 You also specified: 您还指定了:
[project has a] list of current members of that project [项目有]该项目的当前成员列表
This implies that a projet can have several users . 这意味着一个项目可以有多个用户 。
In conclusion , you need a many-to-many relation between your User and Project models. 总之 ,您需要在用户模型和项目模型之间建立多对多关系 。
This is a basic many-to-many relationship in Rails: 这是Rails中的基本多对多关系:
class User < ActiveRecord::Base
has_many :user_projects
has_many :projects, through: :user_projects
class Project < ActiveRecord::Base
has_many :user_projects
has_many :users, through: :user_projects
class UserProject < ActiveRecord::Base
belongs_to :user
belongs_to :project
validates :user_id, :project_id, presence: true
UserProject
model is a join table. UserProject
模型是一个UserProject
表。 What I have done in my code is an explicit has_and_belongs_to_many
, which let you have more control over the join table. 我在代码中所做的是一个显式的has_and_belongs_to_many
,它使您可以更好地控制has_and_belongs_to_many
表。 (example: add a role
column in the UserProject
table, containing data like project_creator
or simple_member
) (示例:在UserProject
表中添加一个role
列,其中包含诸如project_creator
或simple_member
类的数据) UserProject
model could be named Membership
to be more explicit. UserProject
模型可以更明确地命名为Membership
。 I used both models' name to make UserProject
, as we usually do in Rails' naming convention. 我使用两个模型的名称来制作UserProject
,就像在Rails的命名约定中一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.