开发者

Help with Rails ActiveRecord managing queries

开发者 https://www.devze.com 2023-01-13 03:52 出处:网络
I have 3 models. Users, Groups, Employees all of the three have many to many. user has many groups groups have many users

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


This might work for you...

class User < ActiveRecord::Base
  has_many :departments
  has_many :groups, :through=>:departments **, :include => :employee** 

  has_many :employees, :through=>:departments, :source => :group
end


User.find(4).groups.collect { |c| c.employee.size }
0

精彩评论

暂无评论...
验证码 换一张
取 消