繁体   English   中英

Ruby On Rails:如何保持has_one关系和另一个has_one作为单独的名称/

[英]Ruby On Rails: How to keep has_one relation and another has_one as a separate name/

我想要实现的是一个具有以下简单设置的学徒关系

class Apprentice
   attr_accessible :apprentice, :mentor, :other_details
   has_one :employee #contains the apprentice information
   has_one :employee #contains the mentor information
end
class Employee
   attr_accessible :name, :age, :gender
end

我怎样才能使员工既是学徒又是学徒的导师? 另外,由于我还有其他需要使用它的对象,所以我使Employee多态。

非常感谢你的帮助。

我认为这是您追求的目标:

class Employee < ActiveRecord::Base
  has_one :mentor, :class_name => 'Employee', :foreign_key => 'mentor_id'
  has_one :apprentice, :class_name => 'Employee', :foreign_key => 'apprentice_id'
end

我认为最适合您描述的问题的是一种自我参照关系,即“一名雇员有一位导师”。 您的模型可能如下所示:

# id - PK of the employee
# name - Name of the employee
# age - Age of the employee
# gender - Gender of the employee
# mentor_id - The employee's mentor
class Employee
  belongs_to :mentor, class_name: "Employee"
end

这样,您可以通过搜索mentornil雇员来找到所有的学徒,并且可以通过搜索mentornil雇员来找到所有的学徒。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM