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