Reputation: 142
I have a model User and Project in Rails. A Project have a owner (User) and multiple people working on it (User). I have tried this model
class Project < ActiveRecord::Base
belongs_to :owner, class_name: "User"
has_many :users
end
class User < ActiveRecord::Base
has_secure_password
has_many :projects
end
But then was unable to put values into the record for association. Can someone suggest me what to do. (I need to get what projects a user own, works on. Project's owner and people who work in it) Thanks
Upvotes: 1
Views: 323
Reputation: 34338
One way of designing the models would be to have a separate ProjectOwner
and ProjectUser
models both of them are inherited from User
model.
and having has_and_belongs_to_many association between Project
and ProjectUser
models.
class Project < ActiveRecord::Base
belongs_to :project_owner
has_and_belongs_to_many :project_users
end
class User < ActiveRecord::Base
has_secure_password
# other common attributes here
end
class ProjectOwner < User
has_many :projects
end
class ProjectUser < User
has_and_belongs_to_many :projects
end
Add a project_owner_id
column in your projects
table.
Create a join table project_users_projects
which will look like this:
create_table :project_users_projects, id: false do |t|
t.belongs_to :project_user, index: true
t.belongs_to :project, index: true
end
Then, you will be able to do things like these:
project_owner = project.project_owner
project_owner_projects = project_owner.projects
project_user_projects = project_user.projects
project_users = project.project_users
Upvotes: 2