惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V2EX - 技术
V2EX - 技术
酷 壳 – CoolShell
酷 壳 – CoolShell
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
阮一峰的网络日志
阮一峰的网络日志
GbyAI
GbyAI
The Cloudflare Blog
小众软件
小众软件
MyScale Blog
MyScale Blog
IT之家
IT之家
H
Help Net Security
宝玉的分享
宝玉的分享
V
Visual Studio Blog
Hugging Face - Blog
Hugging Face - Blog
F
Fortinet All Blogs
博客园_首页
S
SegmentFault 最新的问题
MongoDB | Blog
MongoDB | Blog
The Hacker News
The Hacker News
有赞技术团队
有赞技术团队
Microsoft Security Blog
Microsoft Security Blog
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
P
Palo Alto Networks Blog
博客园 - 聂微东
罗磊的独立博客
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Engineering at Meta
Engineering at Meta
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
U
Unit 42
Spread Privacy
Spread Privacy
NISL@THU
NISL@THU
Cisco Talos Blog
Cisco Talos Blog
Last Week in AI
Last Week in AI
L
Lohrmann on Cybersecurity
J
Java Code Geeks
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Cyberwarzone
Cyberwarzone
G
Google Developers Blog
C
Cybersecurity and Infrastructure Security Agency CISA
大猫的无限游戏
大猫的无限游戏
Microsoft Azure Blog
Microsoft Azure Blog
L
LangChain Blog
The GitHub Blog
The GitHub Blog
Jina AI
Jina AI
Blog — PlanetScale
Blog — PlanetScale
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LINUX DO - 热门话题
T
Tailwind CSS Blog
雷峰网
雷峰网
C
Cisco Blogs

博客园 - Cure

Oracle 查看哪个表被锁定,并获取对应的sessionID Yii框架常见问题汇总 Yii框架中安装srbac扩展方法 Yii框架中使用PHPExcel导出Excel文件 Yii框架中使用SRBAC作为权限管理模块时遇到的问题 文件名过长,无法删除的解决办法 Yii框架中使用bootstrap SilverLight中显示上标,下标,平方 10 Websites To Download Free HTML/CSS Templates 经过两天的努力,终于写出了第一个android的helloword sqlplus 帮助无法显示问题的解决 COBOL中USAGE的用法 asp.net mvc开发项目的部署?? 初试asp.net mvc感受 临时搞两天VC,在VC里如何获取当前程序的名字和路径以及如何分割字符串 Ruby on rails开发从头来(五十九)- ActiveRecord基础(预加载子记录) Borland以2300万美元卖掉CodeGear开发工具部门 下载安装了ubuntu 8.04,感觉很好很强大 项目管理工具Redmine + SubVersion + Apache + windows环境安装搭建
Ruby on rails开发从头来(五十八)- ActiveRecord基础(自关联)
Cure · 2008-05-07 · via 博客园 - Cure
 

或许存在这样的情况,在一个表中,一条记录关联到表中的另一条记录,例如,公司中的每个雇员都有上级和下级,而他们同时又是雇员,在Rails中你可以这样使用Employee类:

class Employee < ActiveRecord::Base

belongs_to :manager,

:class_name => "Employee",

:foreign_key => "manager_id"

belongs_to :mentor,

:class_name => "Employee",

:foreign_key => "mentor_id"

has_many :mentored_employees,

:class_name => "Employee",

:foreign_key => "mentor_id"

has_many :managed_employees,

:class_name => "Employee",

:foreign_key => "manager_id"

end

让我们使用一些数据,这里雇员ClemDawn都有上级和下级:

Employee.delete_all

adam = Employee.create(:id => 1, :name => "Adam")

beth = Employee.create(:id => 2, :name => "Beth")

clem = Employee.new(:name => "Clem")

clem.manager = adam

clem.mentor = beth

clem.save!

dawn = Employee.new(:name => "Dawn")

dawn.manager = adam

dawn.mentor = clem

dawn.save!

现在我们可以通过关联,来回答“X的下属是谁?”,“Y的上级是谁?”。

p adam.managed_employees.map {|e| e.name} # => [ "Clem", "Dawn" ]

p adam.mentored_employees # => []

p dawn.mentor.name # => "Clem"