简体   繁体   中英

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:

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
  • The UserProject model is a join table. 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. (example: add a role column in the UserProject table, containing data like project_creator or simple_member )
  • The UserProject model could be named Membership to be more explicit. I used both models' name to make UserProject , as we usually do in Rails' naming convention.

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