Situation
In my application a user can create a plan. Once the plan is created, the user can define the stakeholders/team members of the plan. Each team member becomes a responsibility assigned. There are many plans and users can be stakeholders of multiple plans and in each plan they have a different responsibility.
Example
Admin creates a plan and assigns 10 users as stakeholders. 1 is accountable, 2 are responsible, 7 just need to be informed
What I did so far
I set up a has_many through relationship between two models:
class User < ActiveRecord::Base
has_many :assignments
has_many :plans, through: :assignments
end
class Plan < ActiveRecord::Base
has_many :assignments
has_many :users, through: :assignments
end
The assignment table looks like this:
create_table :assignments do |t|
t.belongs_to :user
t.belongs_to :plan
t.string :responsibility
end
add_index :assignments, [:user_id, :plan_id]
the column responsibility contains one of 4 different values (responsible, accountable, informed, consulted.)
What I am looking for
I know how I can query all users that have been assigned to the plan (@plan.users.to_a
) but I do not know how I can additionally supplement the user information with the responsibility they have in this plan.
The query I need is something along the lines of:
Select users which belong to plan X by looking at the assignment table. Do not just use the assignment table to identify the user, but also take the value from the responsibility column in the assignment table and return an array which contains:
- user.first_name
- user.last_name
- user.responsibility (for this specific plan)