[Rails] 真得瞭解 Active Record Lazy loading 嗎?

If inherit active record , use instance to catch value will has lazy loading

所以在 Controller or Model 都會有效果
所以宣告 instance value 不會有 sql 查詢才是

1
@account  = current_user.account

@account 被頁面調用时,才會執行 sql 去查 Account table

1
@account.balance

以上我們的認知是没有錯的,可以参考這篇

But rails is too smart

實際去驗證其實 rails 會跟妳組合的 sql 去判斷是否觸發 lazy loading

舉個例子:

如果是 User has many account 那會在調用處,頁面調用時跑 sql 查找 Account table

1
@account  = current_user.account

如果是 User has many account 卻只查找一個,會直接跑 sql 查找 Account table

1
@account  = current_user.account.find_by(id: params[:id])

User has one account 那無論如何都會直接跑 sql 查找 Account table

1
@account  = current_user.account

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×