rubyonrails:Ruby on rails开发从头来( 5十 3)- ActiveRecord基础(表关联)

  很多使用数据库都包含有多个表而且通常些表的间还有关联关系订单常含有多个条目个条目又关联到种商品个商品可能又属于多个商品分类个商品分类里又包含有多个区别商品

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

price = line_item.product.price

  而不愿像下面这样麻烦:

product_id = line_item.product_id
product = Product.find(product_id)
price = product.price


  Active Record可以帮助我们作为ORM部分Active Record将低级别数据库中外键转换成高级别对象间映射处理了 3种基本情况:

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

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

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

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

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


  在上面DDL中订单和条目关联条目又关联到具体商品注意这里命名约定外键名字product_idproduct是products表单数形式然后再加上表主键名字_id构成外键名

  上面DDL中订单和条目是对多关系还有种是多对多关系例如种商品属于多个商品分类个商品分类又含有多种商品对这种情况通常我们使用第 3个表叫做结合表这个表只包含两个要关联id:

create table products (
id not null auto_increment,
title varchar(100) not null,
/* . . . */
primary key (id)
);
create table categories (
id not null auto_increment,
name varchar(100) not null,
/* ... */
primary key (id)
);
create table categories_products (
product_id not null,
category_id not null,
constra fk_cp_product foreign key (product_id) references products(id),
constra fk_cp_category foreign key (category_id) references categories(id)
);


  注意结合表命名在这里Rails约定为两个表名中间用下划线分开表名按照字母排序Rails会自动找到categories_products表将categories表和products链接起来如果你没有按照约定那么就要自己声明以便Rails能够找到它

Tags:  rubyonrails安装 rubyforrails rubyrails rubyonrails

延伸阅读

最新评论

发表评论