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.