我有3个型号。 Users
,Groups
,Employees
这三者中的所有人都有很多人。
所以我创建了两个新模型:
Departments
(处理Users
和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
我认为我遇到的最大问题是弄清楚如何为用户获取select * from employees where id in (select employee_id from employments where group_id in (select group_id from departments where user_id = 4))
。在sql中,它可以使用此查询:
{{1}}
答案 0 :(得分: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 }