I'm working on a new app in Rails 3 but I'm not sure how can I build the relations between the models.
Basically I have a model User
and a model Project
. An user can create a Project, becoming the project owner. But any other user besides the project owner can join this project as well, but as team member.
Would I need to create a new model for this team relationship? And how would be the relations among this all?
Thanks in advance.
Sounds like
Project
model will have both "belongs_to :user" (admin of the project) and "has_many :users" (participants). I have never tried it personally though. At the same timeUser
model will be more complex.Overall I think it makes more sense to make a "many-to-many" relationship between
User
andProject
and "assign" roles to users (like admin,participant, etc) per project.So diagramming your model I would expect you have the following:
This means a user can be associated with many projects and a project can be associated with many users with 1 owner. Your tables would then have:
Your models would then look like:
That should be enough to get your started
I'm doing something similar with a photo gallery that has shared permissions. Here is roughly the structure I've given it (though this is adapted from another project so may not be exactly right).
Basically, this allows a project to have both an owner that's a user and a bunch of other members that are also users, and they can be accessed separately as such. These are related using a
has_many :through
relationship, and we're basically giving a more meaningful name than what the defaulthas_many :users
would give us.This also gives individual members the ability to join a project by creating a new
project_membership
object for said project, while still maintaining a single owner.Check out this Rails Guide on associations (relationships).
There are a number of ways to set this up each with its own pros and cons. Reading through the guide above should give you a pretty good understanding of the various options available.
You are probably going to end up with a many-to-many association (a project can have many users and a user can have many projects). There you have two main choices:
has_and_belongs_to_many
orhas_many :through
. The first is the most "automagic" but the latter offers more control. The latter is my personal preference.Like I said, read the rails guides so you know what your options are.