I have 3 models. Users
, Groups
, Employees
all of the three have many to many.
- user has many groups
- groups have many users
- groups have many employees
- employees have many groups
So I've created two new models:
Departments
(handles many to many betweenUsers
andGroups
)Employments
(handles many to many betweenGroups
andEmployees
)
I believe I have this correct on paper but I can not get it down to code properly as I am new to rails. Because of this the data fetch does not seem to be correct.
This is what I have: Employment:
class Employment < ActiveRecord::Base
belongs_to :group
belongs_to :employee
end
Department:
class Department < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
User:
class User < ActiveRecord::Base
has_many :departments
has_many :groups, :through=>:departments
has_many :employees, :through=>:departments, :source => :group
end
Group:
class Group < ActiveRecord::Base
has_many :departments #new
has_many :users, :through => :departments #new
has_many :employments
has_many :employees, :through => :employments
end
Employee:
class Employee < ActiveRecord::Base
has_many :employments
has_many :groups, :through => :employments
end
I think biggest problem I have is to figure out how to get total employees
for a user. In sql it would work with this query:
select * from employees where id in (select employee_id from employments where group_id in (select group_id from departments where user_id = 4))