Karim Magdy Mansour
Karim Magdy Mansour

Reputation: 316

has_many of the same table through several others

What am trying to do is: i have a User model and i have a Task model Task has 2 types of users Owners and Supervisors all of them are users !

so what i have so far is:

Task Model

class Task < ActiveRecord::Base
  has_many :task_owners, dependent: :destroy
  has_many :task_supervisors, dependent: :destroy
  has_many :users, through: :task_owners
  has_many :users, through: :task_supervisors
end

TaskSupervisor Model

class TaskSupervisor < ActiveRecord::Base
  belongs_to :task
  belongs_to :user
end

TaskOwner Model

class TaskOwner < ActiveRecord::Base
  belongs_to :task
  belongs_to :user
end

and finally the User Model

class User < ActiveRecord::Base
  has_many :task_owners
  has_many :task_supervisors
  has_many :tasks, through: :task_owners
  has_many :tasks, through: :task_supervisors
end

now as you can imagine ... my problem is when i get a task and retrieve the users i only get one of my associations ... what i need is a way to change the getters name or identify them some how basically to be able to say something like

task.owners
task.supervisors

Upvotes: 1

Views: 275

Answers (1)

j-dexx
j-dexx

Reputation: 10416

class Task < ActiveRecord::Base
  has_many :task_owners, dependent: :destroy
  has_many :task_supervisors, dependent: :destroy
  has_many :owners, through: :task_owners, source: :users
  has_many :supervisors, through: :task_supervisors, source: :users
end

You should be able to do this.

Then you should get your task.owners and task.supervisors

Edit:

You will need to change your user model to

class User < ActiveRecord::Base
  has_many :task_owners
  has_many :task_supervisors
  has_many :owned_tasks, through: :task_owners, source: :tasks
  has_many :supervised_tasks, through: :task_supervisors, source: :tasks
end

Upvotes: 1

Related Questions