Rails的模型自关联
来源:互联网 发布:js返回上一页不刷新 编辑:程序博客网 时间:2024/06/05 04:27
关于Rails的模型自关联有一个非常有意思的题目,大概是这样的:
lisa = Person.create(name:'Lisa')tom = Person.create(name:'Tom',parent_id:lisa.id)andy = Person.create(name:'Andy',parent_id:lisa.id)tom.parent.name => 'Lisa'lisa.children.map(&:name) => ['Tom','Andy']thomas = Person.create(name: 'Thomas',parent_id: tom.id)peter = Person.create(name:'Peter',parent_id:tom.id)gavin = Person.create(name:'Gavin', parent_id: andy.id)lisa.grandchildren.map(&:name) => ['Thomas','Peter','Gavin']
问如何定义Person模型来满足以上需求?
题目考察了对模型自关联的理解,通过审题我们可以得出以下几点:
- Person对象的Parent同样是Person对象(自关联)
- Person对象对Parent是多对一关系
- Person对象对Children是一对多关系
- Person对象通过Children与GrandChildren建立了一对多关系
在不考虑GrandChildren时,不难得出模型定义如下:
class Person < ActiveRecord::Base belongs_to :parent, class_name: 'Person', foreign_key: 'parent_id' has_many :children, class_name: 'Person', foreign_key: 'parent_id' end
其中Person包含两个自关联关系:
- 第一个就是非常常见的从子到父的关系,在Person对象创建时指定parent_id来指向父对象;
- 第二个关系用来指定Person对象对应的所有子对象
接下来更近一步,我们要找到Person对象子对象的子对象,换句话说:孙子对象。
如我们上面的分析,Person对象通过Children与GrandChildren建立了一对多关系,其代码表现为:
has_many :grandchildren, :through => :children, :source => :children
:source
选项的官方文档说明如下:
The :source option specifies the source association name for a has_many :through association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name. —— rails guide
在这里我们通过:source
选项告诉Rails在children对象上查找children关联关系。
于是该题目完整的模型定义如下:
class Person < ActiveRecord::Base belongs_to :parent, class_name: 'Person', foreign_key: 'parent_id' has_many :children, class_name: 'Person', foreign_key: 'parent_id' has_many :grandchildren, :through => :children, :source => :childrenend
参考:Need help to understand :source option of has_one/has_many through of Rails
阅读全文
0 0
- Rails的模型自关联
- rails 自关联、批写入、layout布局的选择顺序
- rails 自关联、批写入、layout布局的选择顺序
- rails:simple_for 对于关联模型的特殊技巧
- rails中的模型关联(进阶篇)
- rails中的模型关联(进阶篇)
- rails中模型的关联关系 一对一、一对多、多对多及named_scope
- rails中模型的关联关系 一对一、一对多、多对多及named_scope
- rails 自关联 删除父节点删除子节点
- 关联模型主被动关联的区别
- ruby on rails 新建模型,模型间设置关联,表单验证
- 模型的自转化
- ThinkPHP中坑爹的关联模型
- thinkphp5 模型关联的bug
- ThinkPHP3.2的关联模型
- Rails的模型支持:Active Record
- Rails框架下的简单Blog模型
- ruby on rails 的模型测试
- 计算机视觉小实例 No.2 基于形态学的权重自适应图像去噪
- python006 Python3 运算符
- 推介一个Python教程网站
- 中文出身的妹纸,零基础学习JAVA靠谱么
- WebGL之旅(十四)点光源
- Rails的模型自关联
- python007 Python3 数字(Number)
- [kuangbin带你飞]专题二 搜索进阶 I
- Synchronized下的三种锁升级场景解读
- 全排列(Java)
- 使用URDF创建机器人3D仿真模型
- python008 Python3 字符串
- 认证机构信息管理软件
- 北大方正集团的“三阶段发展论”必须彻底批判,肃清流毒