---
title: "ruby on rails表间关联"
author: "gift5168xf"
date: "2009-10-08T20:07:00Z"
tags: []
slug: "ruby-on-rails"
draft: false
lastmod: "2009-10-14T01:41:50Z"
id: 487574
url: "https://sufery.iteye.com/blog/487574"
---

**1** **创建外键**

t.integer : 表名单数 \_id

关联表的命名要以首字母的顺序决定如 categories\_products

关联表的联合索引： add\_index:categories\_products,\[:product\_id,:category\_id]

**2** **模型对象中指定关联**

**一对一关联**

belongs\_to:order has\_one:invoice

**一对多关联**

belongs\_to:order has\_many:ling\_items

**多对多关联**

has\_and\_belongs\_to\_many:products

**3 belongs\_to** **声明（当前对象有一个父对象）**

belongs\_to 接受一个 hash 参数： ( 如果改变关联名称 )

：自定义父对象属性名，

：父对象类名 (:class\_name) ，

：外键名 (:foreign\_key) ，

：条件 (:conditions)

具有下列方法： .product 返回关联对象

.product=obj 设置关联对象

.build\_product(attributes{}) 新建一个关联对象

.create\_product(attributes{}) 新建并保存一个关联对象

**4 has\_one()** **声明（当前对象有一个子对象）**

has\_one 接受一个 hash 参数：（除 belongs\_to 的参数还有）

： dependent =&gt; 值为：

： destroy 删除父记录的同时删除子表的关联记录

： nullify 删除父记录之后留下子记录，同时将记录外键置 null

： false 删除父记录时不改变子记录的任何

具有下列方法： .invoice 返回关联对象

**5 has\_many()** **声明**

接受一个 hash 参数（包括 has\_one 的所有键值对）

： order=&gt;”xxx,yyy DESC” 查询时按照 xxx ， yyy 降序得到数组

具有下列方法： .orders 返回关联对象

.orders.replace() 替换为新的一组 orders 对象

.orders.destroy\_all

.orders.clear 解除所有关联（把外键置为 NULL ）

.orders.find() find 方法与所有的 find 方法一样

**6 has\_and\_belongs\_to\_many()** **声明**

具有前面的所有参数和方法

**7** **把模型类映射成为连接表**

在不作为连接表的模型中除了加入 has\_many: 被作为连接表的模型复数，还要加入一个 has\_many: 与之进行实际关联的模型复数 , :through=&gt;:readings

与 has\_many 可以改变关联名称如：

has\_many: 自定义的关联名称复数 , :through=&gt;xxx , :source=&gt;: 实际关联的模型（注意不是复数 ）

当通过关联模型表找到的数据可能是多条一样的这里通过在 has\_many 的后面在加入一个参数来去掉重复 :unique=&gt;true 这是在 ActiveRecord 中实现的；若在数据库中则在 has\_many 中要加入查询条件参数 :select=&gt;”distinct users.\*”

**8** **扩展关联（既关联时加入关联的条件）**

在 has\_many 后加入语句块并定义一个给条件时的关联查找 如：

has\_many :articles, :through=&gt;:readings **do**

**def** rated\_at\_or\_above(xxxx)

find :all, :conditions=&gt;xxxx

**end**

**end**

用时： good\_articles=user.articles.rated\_at\_or\_above(xxxx)

共享关联方法时则把方法放入模块中然后在 has\_many 后家如参数

:extend=&gt; 模块名称

**9** **连接多张表**

**1** **）单表集成（用于属性重复率比较高的模式）**

一张数据库表中存有说有继承与被集成的属性字段

继承时只要在模型首部标记 Customer&lt;Person 等

对于继承之间的关联只需要在表中设置好关联的字段，在用 belongs\_to 的自定义方法来定义与被继承之间的关系

**2** **）多态关联（用于属性重复率比较少的模式）**

每个多态一张表

在引用多态的模型的表中建立外键 关联名 \_id ，关联名 \_type 两个字段；模型中则 belongs\_to : 关联名 , :polymorphic=&gt;true 注： polymorphic 表示多态

在每个多态模型中建立 has\_one : 引用此多态的模型名 , :as=&gt;: 关联名

用时：引用多态的模型 . 关联名 = 某一个多态对象