How can a record belong_to a single user, but also have multiple "secondary" users?
In my app, I have a User model and a Project model. A user has_many assignments and each project belongs_to a user. But along with each project having an owner, the user who created it, I would like the owner be able to share it with others (so that the project gets shown on the other users' account along with their own). I imagine having to use has_many :through, and setting up a projects_users table with a user_id and a project_id. And I guess this would be the end result?
Project.first.user
# The creator of the project
=> #<User id: 1, name: 'andrew', etc...>
Project.first.users
# The users that the creator chose to share it with
=> [#<User id: 2 ...>, #<User id: 3 ...>]
I've been working on this a bit, and I created a SharedProject model with a user_id and project_id column:
class SharedProject < ActiveRecord::Base
belongs_to :user
belongs_to :project
end
I would like to call both user.projects and user.shared_projects, but I don't know how I would get shared_projects to return project records instead of records from the shared_projects table. I can't do has_many :projects, :through => :shared_projects
since then I wouldn't be able to return projects that the user has created.
class User < ActiveRecord::Base
has_many :projects # Calling user.projects returns the projects that user created
has_many :shared_projects # How to get user.shared_projects to return project records?
开发者_运维百科end
Here's how you can add an owner field to your Project
model and then and owned projects collection to your User
model. You can use what you already have for the shared projects part.
class User < ActiveRecord::Base
has_many :owned_projects, :class_name => 'Project', :foreign_key => 'owner_id'
end
class Project < ActiveRecord::Base
belongs_to :owner, :class_name => 'User'
end
You'll need to add an owner_id
column to your projects
table.
Just of the top of my head, I think you might want to set up a ProjectShare model.
The ProjectShare model will belong_to user (the sharer), belong_to project (the project being shared) and has_many user_shared_with (just a different classname for user model)
This way you could see who exactly has shared what with who. I think you'd could accomplish the same thing with the has_many :through situation by just naming your models accordingly.
精彩评论