I have a User and Project model. A user can have multiple projects, and a project can have multiple users. This of course is simple with a has_and_belongs_to_many association. My problem is that I’d also like to track the user who created the project. This would be simple with a belongs_to :user for my Project model. The problem then is that doing a has_many :projects for a User when a user already has a HABTM relationship with a Project makes little sense.
Here’s what I would eventually like to achieve:
# building a project with the currently logged in user
current_user.projects.build(...)
# now when a user wants to add another user to this project
project = current_user.projects.find(...)
project.users << User.find(...)
# grabbing information
some_project.user #=> The user who created this project
some_project.users #=> The array of User objects associated
some_user.projects #=> The array of Project objects associated
In the future it’s likely a User will have the same sort of relationship with a Group, where a User would both have many and belong to many groups. But again I would also like to track the creator of this Group.
It’s quite likely I’m missing something. What’s a common way to achieve this?
If it helps to clarify, a possible configuration is laid out below:
- Group
- has_and_belongs_to_many :users
- belongs_to :user
- has_many :projects
- Only a
Usershould have the ability to create aGroup
- User
- has_and_belongs_to_many :groups
- has_many :projects
- Can great a group or a project, and can also belong to both
- Project
- has_and_belongs_to_many :users
- belongs_to :group
- both a
Userand aGroupshould have the ability to create aProject
I’ve also tried doing simple has_and_belongs_to_many for each association and including a creator_id for example, and tracking this myself. For example.. Project.create(:creator_id => current_user.id) but this seemed hackish and I was sure they would be a better way to do this. Apologies for my ignorance if I’ve missing something simple.
Reading this again you want to have one owner of the project, either a group or a user. Store that as a polymorphic belongs_to relationship from the project model. ie. owner_type => ‘User’/’Group’ owner_id => 123
Other users associated with the group are many to many so you need a join table.
Your group model is a separate model with a many to many relationship with users so you can simply store the user who created it as a field of the group model ie. :user_id 123.