views:

37

answers:

1

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 between Users and Groups)
  • Employments (handles many to many between Groups and Employees)

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))
A: 

If you defined your many-to-many ActiveRecord model correctly.

You can do this to find the employees that are associated with the user:

@user = User.find(params[:id])
@employees = @user.employees

If you would like to tweak your queries, check out this doc - http://guides.rubyonrails.org/active_record_querying.html

This will allow you to do everything from eager/lazy loading, joining, grouping, limiting, etc.

If you want to use your original SQL to figure things out before you write cleaner code, check out the "finding-by-sql" section on the same page.

Synthesis