2010-08-25 90 views
0

我有3個模型。 UsersGroups,Employees所有這三個都有很多。幫助Rails ActiveRecord管理查詢

  • 用戶有很多組
  • 組有許多用戶
  • 羣體有多少員工
  • 員工有許多團體

所以,我創建了兩個新型號:

  • Departments(在之間處理多對多和Groups
  • Employments(處理多對多GroupsEmployees之間)

我相信我有這個正確的紙張上,但我不能讓它下來代碼正確,因爲我是新來的軌道。由於這個原因,數據提取似乎並不正確。

這是我有: 就業:

class Employment < ActiveRecord::Base 
    belongs_to :group 
    belongs_to :employee 
end 

部:

class Department < ActiveRecord::Base 
    belongs_to :group 
    belongs_to :user 
end 

用戶:

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

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

組:

class Group < ActiveRecord::Base 
    has_many :departments #new 
    has_many :users, :through => :departments #new 

    has_many :employments 
    has_many :employees, :through => :employments 
end 

員工:

class Employee < ActiveRecord::Base 
    has_many :employments 
    has_many :groups, :through => :employments 
end 

我覺得我有最大的問題是要弄清楚如何獲得total employees給用戶。在SQL它會與此查詢工作:

select * from employees where id in (select employee_id from employments where group_id in (select group_id from departments where user_id = 4)) 

回答

0

這可能會爲你工作...

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 }