回上一頁

Ruby撈資料時避免N+1 技術分享筆記

N+1是個常犯的錯誤,會造成效能差的取資料方式。

 

解決方法

在操作Model時能用 includes 就可以盡量使用,配合關聯來取得。

ex. post Model 

  
    belongs_to :user
  

ex. 下面是controllar例子:

  
    Model.includes(:user)
  

...

 

參考資料:

https://charliereese.ca/rails-performance-3-tips-for-removing-n-1-queries/