【问题标题】:Ruby On Rails: How to keep has_one relation and another has_one as a separate name/Ruby On Rails:如何保持 has_one 关系和另一个 has_one 作为单独的名称/
【发布时间】:2023-03-24 17:08:01
【问题描述】:

我想要通过如下简单设置实现学徒关系

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 具有多态性。

非常感谢您的帮助。

【问题讨论】:

  • 嗨,Marc,感谢您编辑我的笔记。你是怎么把所有的空间都没有 html 的?

标签: ruby-on-rails activerecord has-one


【解决方案1】:

我想这就是你所追求的:

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

【讨论】:

  • 谢谢。我会试试这个。
【解决方案2】:

我认为最适合您所描述的问题的是自我参照关系,其中“员工有导师”。您的模型可能如下所示:

# 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的员工找到所有的学徒,你可以通过搜索mentor不是nil的员工找到所有的导师。

【讨论】:

  • 谢谢。 Employee 与一堆其他对象具有多态的 belongs_to 关系。我还能让它自引用而不丢失多态性吗?
  • 这将适用于您要添加到Employee 的任何其他类型的关系。如果您不熟悉架构设计(外键),我建议您对其进行一些研究,以便您了解幕后究竟发生了什么。
  • 听起来不错。将来我一定会尝试自我参照关系。我可以深入挖掘的任何来源?目前我正在使用 has_one :apprentice, class_name: 'Employee', conditions: "role = 'apprentice'", as: :polymorphic。目前这似乎工作正常。有什么想法吗?
  • 有几种方法可以在 Ruby on Rails 中生成关联,因此只要您的解决方案有效,您就应该很好。为了更深入地研究这类事情,我真的会推荐任何初级 SQL 课程。一个 Google 查询应该可以为您带来不少这样的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-23
相关资源
最近更新 更多