Welcome 微信登录

首页 / 软件开发 / JAVA / Ruby on rails开发从头来(五十三)- ActiveRecord基础(表关联)

Ruby on rails开发从头来(五十三)- ActiveRecord基础(表关联)2011-12-04 博客园 Cure很多程序使用的数据库都包含有多个表,而且通常一些表之间还有关联关系,订单常含有多个条目,而一个条目又关联到一种商品,一个商品可能又属于多个商品分类,一个商品分类里又包含有多个不同的商品。

在数据库中,这些关联表现为使用主键值把表关联起来,也就是外键,但是这属于底层的范畴,我们需要处理Model对象间的关联,而不是数据库中的列和键。如果一个订单含有多个条目,我们需要有办法来维持,处理它们的关系,如果一个条目引用到一种商品,我们或许想这样做:

price = line_item.product.price
而不愿像下面这样麻烦:

product_id = line_item.product_idproduct = Product.find(product_id)price = product.price
Active Record可以帮助我们,作为ORM的一部分,Active Record将低级别的数据库中的外键转换成高级别的对象间的映射。处理了三种基本情况:

A表中的一条记录和B表的零条或一条记录相关联。

A表中的一条记录和B表的任意多条记录相关联。

A表中的任意多条记录和B表的任意多条记录相关联。

下面我们来看看怎样创建外键(Foreign Key),我们使用下面的DDL来创建表,它们之间指定了关联:

create table products (id int not null auto_increment,title varchar(100) not null,/* . . . */primary key (id));create table orders (id int not null auto_increment,name varchar(100) not null,/* ... */primary key (id));create table line_items (id int not null auto_increment,product_id int not null,order_id int not null,quantity int not null default 0,unit_price float(10,2) not null,constraint fk_items_product foreign key (product_id) references products(id),constraint fk_items_order foreign key (order_id) references orders(id),primary key (id));