帮助Rails ActiveRecord管理查询

时间:2010-08-25 05:11:39

标签: ruby-on-rails activerecord

我有3个型号。 UsersGroupsEmployees这三者中的所有人都有很多人。

  • 用户有很多小组
  • 群组有很多用户
  • 团体有很多员工
  • 员工有很多小组

所以我创建了两个新模型:

  • Departments(处理UsersGroups之间的多对多
  • 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

我认为我遇到的最大问题是弄清楚如何为用户获取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}}

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 }