Ruby on Rails development from scratch (57)-ActiveRecord Foundation (Many-to-many Association Relationship)

Source: Internet
Author: User
Tags table name ruby on rails

Many-to-many associations in rails are implemented by declaring Has_and_belongs_to_many in the class corresponding to the associated table.

In a database, Many-to-many associations are implemented using an intermediate table, which includes the primary key of the associated table, and the Active record assumes that the name of the intermediate table is concatenated with the name of the associated table in alphabetical order. For example, the association table is categories and products, and the middle table name is categories_products.

Note that our association table does not have an ID column for two reasons, first of all, do not need a unique identity to identify the connection between two foreign keys, we define the statement of the table as follows:

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
key (foreign) References products (ID),
primary key (category_id, product_id)
);

The second reason does not include an ID column in the intermediate table, and an Active record automatically contains all the columns when accessing a row. If an ID column is included, the ID column will duplicate the ID column in the associated table.

The Has_and_belongs_to_many () statement

Has_and_belongs_to_many is like Has_many,has_and_belongs_to_many in many ways. Creates a property that is essentially a collection that supports the same method as Has_many.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.