2010-08-25 81 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)) 

回答

1

如果您正确定义了多对多ActiveRecord模型。

为此,您可以找到与该用户相关联的员工:

@user = User.find(params[:id]) 
@employees = @user.employees 

如果你想调整你的查询,看看这个文档 - http://guides.rubyonrails.org/active_record_querying.html

这将允许你做任何事情从急切/延迟加载,加入,分组,限制等。

如果您想在编写更干净的代码之前使用您的原始SQL来计算事情,请查看“查找sql​​”部分相同的页面。