實際應用的資料庫通常包含多張表且彼此關聯。ActiveRecord 作為 ORM 層,將底層外鍵轉換為高層級的物件導航,讓開發者能撰寫 price = line_item.product.price 而非手動拼湊 SQL。
以訂單、明細、商品為例:
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) );
命名慣例:外鍵名 = 參照表單數形式 + _id(如 product_id 參照 products 表)。
商品與分類為多對多,需中間表 categories_products:
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 會自動發現;否則需在宣告中指定 :join_table。