ruby on rails 減少查詢次數

有時間寫代碼比較粗糙,不管代碼質量,這樣會造成查詢次數過多的情況

下面幾個方法可儘量避免

1 使用includes 方法及早加載
Active Record 允許我們提前指明需要加載的所有關聯,這是通過在調用 Model.find 時指明 includes 方法實現的。通過指明 includes 方法,Active Record 會使用盡可能少的查詢來加載所有已指明的關聯

假設有如下代碼,查找 10 條客戶記錄並打印這些客戶的郵編:
categorys = Category.limit(10)
 
categorys.each do|category|
  puts category.articles.first.title
end

上面的代碼第一眼看起來不錯,但實際上存在查詢總次數較高的問題。這段代碼總共需要執行 1(查找 10 條客戶記錄)+ 10(每條客戶記錄都需要加載地址)= 11 次查詢


使用incluses之後

categorys = Category.limit(10)
 
categorys.each do|category|
  puts category.articles.first.title
end

上面的代碼只執行 2 次查詢,而不是之前的 11 次查詢:

SELECT*FROMcategorys LIMIT 10
SELECT articles.* FROM articles WHERE(articles.category_id IN(1,2,3,4,5,6,7,8,9,10))


***注意:includes(:articles) 關聯要在model裏 寫好關係。

classArticle < ApplicationRecord belongs_to:category has_many:comments has_many:tags end classCategory < ApplicationRecord has_many:articles end


2 有時候頁面需要計算 總數量這些數值

比如shop.shop_users.count

會進行  查詢

SELECT COUNT(*) FROM `shop_users` WHERE `shop_users`.`shop_id` = 11

爲避免 應使用size或者length  方法

3 查詢  所有的然後使用group_by 這樣可以直接取,不用像group  方法查詢出來的數據似得需要遍歷匹配

@shoporder_group = ShopOrder.all.group_by{|shoporder| shoporder.shop_id }

遍歷數據的時候使用

@shoporder_group[shop.id].nil? ? 0 : @shoporder_group[shop.id].count













發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章