The “Has And Belongs To Many” relationship, or “habtm”, is also called an “n to m” relationship. It is defined as a relationship between two tables, A and B, that allows one row of A to be related to several rows of B, and one row of B to be related to several rows of A.
Given the mechanism of relational databases, this implies the definition of a third table, A_B (if we use the Akelos naming conventions), with which A and B have a “1 to n” relationship.
For example, in an e-commerce application, users can buy products. Table A becomes our Users table, table B becomes our Products table, and table A_B becomes our products_users table.
In products_users, you will find one foreign key to the users table, as well as one foreign key to the products table, for each row, as well as additional information on how this user got linked to this product.
A more sensible name for table products_users might be “sales”, as this is really what this intermediary table is about in our e-commerce application.
No, Akelos doesn't generate these relations for you, so you will have to define them all by yourself. You should still respect database tables naming conventions though, and keys to the users and products tables should be called user_id and product_id.
* Declare the relationship in your models:
class User extends ActiveRecord{
var $habtm = 'products';
}
class Products extends ActiveRecord{
var $habtm = 'users';
}
* Select a meaningful action name in your controllers to link one object with the other:
UsersController::add_product or ProductController::assign_to_user
* Generate the right table structure in your install migrate script.