有時間寫**比較粗糙,不管**質量,這樣會造成查詢次數過多的情況
下面幾個方法可盡量避免
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 10select articles.* from articles where(articles.category_id in(1,2,3,4,5,6,7,8,9,10))
***注意:includes(
:articles
) 關聯要在model裡 寫好關係。
belongs_to:category
has_many:comments
has_many:tags
end 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_group[shop.id].nil? ? 0 : @shoporder_group[shop.id].count
巧用變數減少查詢
1 用變數排名 例 以ecshop中的商品表為例,計算每個欄目下的商品數,並按商品數排名.select cat id,count as cnt from goods group by cat id order by cnt desc 並按商品數計算這些欄目的名次 set curr cnt 0,pre...
初學Ruby On Rails有感
因為看到一些牛人的部落格裡都有了對ruby on rails的認可,感覺主流的思想開始向rails傾斜了,那麼自己也不得不趕緊跟上,想法弄到了一本 應用rails進行敏捷web開發 之所以選擇它是因為它有rails,有ruby語法的講解還有敏捷一詞.這麼多讓我感興趣的東西集合到一起,我認定這會是一本...
Ruby on Rails版本公升級
公升級rails版本和gem版本時,先 gem update rails gem update 然後它會出現mysql的驅動錯誤的提示如下 問題 the bundled mysql.rb driver has been removed from rails 2.2.please install th...