[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
- 最後加上
--skip-migration
將不會產生 migration 檔。 column:type:option
,options 可以加入index
這裡的 store:references
寫法其實也可以用前面的 store_id:integer
寫法,但 references 的寫法會多做幾件事:
- 自動加上索引(index),加快查詢速度。
- 自動幫 Model 加上
belongs_to
。
column options
index
unique
column type
integer
primary_key
decimal
float
boolean
binary
string
text
date
time
datetime
timestamp
參考範例
##
# price 要記得加上引號
##
rails g model user pseudo:string{30}
rails g model product 'price:decimal{10,2}'
# uniq, references, index
rails g model user email:index location_id:integer:index
rails g model user pseudo:string:uniq
rails g model user username:string{30}:uniq
rails g model photo album:references
rails g model WareHouse store:references product:references
# polymorphic
rails g model product supplier:references{polymorphic}
rails g model product supplier:references{polymorphic}:index
Advanced Rails model generator @ BY ANDREY KOLESHKO
關連類型
- belongs_to
- has_one
- has_many
- has_many :through
- has_one :through
- has_and_belongs_to_many
在使用上面這些 Active Record Association 的方法時, Database 的資料表和欄位必須透過
migration
或model
的 generator 先建立好。