美文网首页ruby on rails
Rails的模型自关联

Rails的模型自关联

作者: 李小西033 | 来源:发表于2017-07-29 04:27 被阅读203次

关于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 => :children
end
result.png

参考:Need help to understand :source option of has_one/has_many through of Rails

相关文章

  • Rails的模型自关联

    关于Rails的模型自关联有一个非常有意思的题目,大概是这样的: 问如何定义Person模型来满足以上需求? 题目...

  • rails模型关联(二)-自联结

    在实际开发的时候会遇到多级分类的需求.如:商品分类.3c分类下可以包含手机、数码、mp3等二级分类,衣服分类下可以...

  • rails模型关联

    rails的orm很完善,可以非常方便的建立模型之间的关联.通过一些简单的代码实现一些常见的关联操作. 关联基础操...

  • [Rails] Active Record Associatio

    资料来源:Rails Guide Guide: -在模型之间构建关联-理解不同种类的关联-使用关联提供的方法 1....

  • 《Rails-Guides》Reading notes five

    Rails 支持六种关联 belongs_to关联 belongs_to关联创建两个模型之间一对一的关系,声明所...

  • Active Record关联

    在开发中常常会涉及到多个模型进行关联的操作.Rails支持六种关联: 为了后续的内容分析,事先创建以下模型 bel...

  • Rails joins & includes &

    又是一个起源于群友(154112964 rails群 欢迎使用rails的所有人)讨论的玩意 先放一些模型&关联在...

  • rails中常用gem

    软删除 acts_as_paranoid 自关联 ancestry 拖拽排序 rails_sortable 避免n...

  • Django模型-自关联

    新建模型AreaInfo,生成迁移 class AreaInfo(models.Model): atitle = ...

  • Django 2.1.7 模型管理器 models.Manage

    上一篇Django 2.1.7 模型的关联讲述了关于Django模型一对多、多对多、自关联等模型关系。 在查询数据...

网友评论

    本文标题:Rails的模型自关联

    本文链接:https://www.haomeiwen.com/subject/skyflxtx.html