0
我有3个模型。 Users
,Groups
,Employees
所有这三个都有很多。Rails ActiveRecord模型设计
- 用户有很多组
- 组有许多用户
- 群体有多少员工
- 员工有许多团体
所以,我创建了两个新型号:
Departments
(在之间处理多对多和Groups
)Employments
(处理多对多Groups
和Employees
之间)
我相信我有这个正确的纸张上,但我不能让它下来代码正确,因为我是新来的轨道。由于这个原因,数据提取似乎并不正确。
这是我有: 就业:
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))