有時間寫代碼比較粗糙,不管代碼質量,這樣會造成查詢次數過多的情況
Model.find
時指明 includes
方法實現的。通過指明 includes
方法,Active
Record 會使用盡可能少的查詢來加載所有已指明的關聯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裏 寫好關係。
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