[Rails] Active Record Association (Model)
速查
- Book
belongs_to
Author: Book 會多 author_id - Supplier
has_one
Account: Account 會多 supplier_id
# 會產生 store_id 和 product_id
$ rails g model WareHouse store:references product:references
有 column_id 的 table 表示在比較下階。
觀念
在處理關連性資料庫時,我們經常需要透過 Query 的 方式找出另一個關連的資料。但是透過 Active Record Association,我們可以更方便的去操作關連性資料庫。
在 Rails 裡所謂的關係,是指在 Model 層級的關係,主要是透過 Model 的方法(例如 has_many
或 belongs_to
)搭配 Rails 的資料表慣例設定主鍵(Primary Key)及外部鍵(Foreign Key),讓這些資料表串在一起。
每一個 association 使用後對應會產生的方法:
- Detailed Association Reference @ RailsGuides
- Active Record Association @ RailsGuides
Generator
# rails g model [ModelClassName <column:type:options>
rails g model WareHouse store:references product:references
rails g model user email:index location_id:integer:index