• Ruby on rails开发从头来(五十三) 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将低级别的数据库中的外键转换成高级别的对象间的映射。处理了三种基本情况:

    -          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)

    );

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

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

    create table products (

    id int not null auto_increment,

    title varchar(100) not null,

    /* . . . */

    primary key (id)

    );

    create table categories (

    id int not null auto_increment,

    name varchar(100) not null,

    /* ... */

    primary key (id)

    );

    create table categories_products (

    product_id int not null,

    category_id int not null,

    constraint fk_cp_product foreign key (product_id) references products(id),

    constraint fk_cp_category foreign key (category_id) references categories(id)

    );

    注意结合表的命名,在这里Rails的约定为两个表名,中间用下划线分开,表名按照字母排序,Rails会自动找到categories_products表将categories表和products链接起来,如果你没有按照约定,那么就要自己声明,以便Rails能够找到它。
  • 相关阅读:
    30个热门的CSS3 Image Hover 脚本
    70个jQuery触摸事件插件 支持手势触摸!
    40个超酷的jQuery动画教程
    45个漂亮且有创意的HTML5网站展示
    40+极具创意的产品展示PSD模板
    25个开始学习HTMLE5的最好的资源
    25个很酷的jQuery倒计时脚本–添加动态计数器!
    45个wordpress自适应插件
    30+WordPress古典风格的主题古典却不失时尚
    为kindeditor上传图片添加水印(PHP版)
  • 原文地址:https://www.cnblogs.com/dahuzizyd/p/ruby_rails_study.html
Copyright © 2020-2023  润新知