【问题标题】:Model association between Company, Employee, and department公司、员工和部门之间的模型关联
【发布时间】:2012-12-26 13:48:32
【问题描述】:

我正在使用 Ruby on Rails 3。并试图绘制出三个模型来模拟公司、员工及其各自部门的数据。

在得出以下解决方案:

class Company < ActiveRecord::Base
  has_many :departments
  has_many :employees, through => :departments
end

class Department < ActiveRecord::Base
  belongs_to :company
  has_many :employees
  has_one :department_description
end

class DepartmentDescription < ActiveRecord::Base
  belongs_to :department
end

class Employee < ActiveRecord::Base
  belongs_to :department
end

这是关联这些模型的“正确”方式吗?

【问题讨论】:

  • 没有理由(鉴于您提供的上下文)为什么您应该为Department:description 提供一个单独的表/模型。将该列添加到Department 并摆脱:department_description 上的has_one 关系
  • 是的,我没有添加任何上下文。但是情况是 has_many :employees,通过 => :departments 有效地使部门表 (DB) 成为连接表,而 DepartmentDescription (姓名、电子邮件等)将是多余的。

标签: ruby-on-rails associations has-many-through


【解决方案1】:

我认为您的上一个回复可以解释为什么您很难找到关联这些模型的正确方法。

您似乎将您的 Department 仅视为一个 join_table,这可能是由于您没有完全理解 has_many => :through 构造,并且它实际上允许您的 Department 成为一个适当的模型其中有许多属性和方法,因此也是一个“描述”属性。

创建单独的DepartmentDescription 模型实际上是一种资源浪费。 Chad Fowler 在他的 Rails 食谱中有几个很好的例子:has_many => through 和嵌套资源...所以看看吧。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-15
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多