Welcome 微信登录

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

Ruby on rails开发从头来(五十七)- ActiveRecord基础(多对多关联关系)2011-12-04 博客园 Cure在Rails中多对多关联通过在关联表对应的类中声明has_and_belongs_to_many来实现。

在数据库中,多对多关联使用中间表来实现,表中包括关联表的主键,Active Record假定这个中间表的名字是由关联表的名字根据字母的顺序串联起来得到的。例如,关联表为categories和products,中间表的名字就是categories_products。

注意我们的关联表没有id列,有两个原因,首先,不需要一个唯一的标识来识别两个外键之间的连接,我们定义表的语句像下面这样:

create table categories_products (category_id int not null,product_id int not null,constraint fk_cp_category foreign key (category_id) references categories(id),constraint fk_cp_product foreign key (product_id) references products(id),primary key (category_id, product_id));
第二个原因在中间表中不包括一个id列,Active Record在访问某个行时会自动包含所有的列。如果包含了一个id列,那么这个id列就会复写掉在关联表中的id列。

The has_and_belongs_to_many() 声明

has_and_belongs_to_many在很多方面很像has_many,has_and_belongs_to_many创建了本质上是一个集合的属性,该属性支持和has_many相同的方法。