【发布时间】:2015-03-02 12:39:36
【问题描述】:
我的模型中有这个方法可以为我的应用程序中的搜索功能提供支持:
def self.get_products(cat_ids, term, min_price, max_price, sort_column, sort_direction, current_store = nil)
products = Product.where(category_id: cat_ids).joins('LEFT JOIN stores ON stores.id = products.store_id')
products = products.order(sort_column + " " + sort_direction)
products = products.where(store_id: current_store.id) if current_store.present?
products = products.where("lower(product_title) like ?", "%#{term}%") if term.present?
products = products.where("price_pennies >= ?", (min_price.to_f/1.2).round * 100) if min_price.present?
products = products.where("price_pennies <= ?", (max_price.to_f/1.2).round * 100) if max_price.present?
products = products.where('stores.opened_to_customers = ?', true)
products
end
上面方法中参数的简要说明:
cat_ids: An array of all the relevant category_ids. In this case, using the awesome_nested_set gem helper
cat_ids = @category.self_and_descendants.pluck(:id)
term: The search query entered by the user
我觉得剩下的参数是非常自我描述的。
这在 2 个月的过程中一直运行良好,但现在产品表中的行已接近 300,000,它变得非常缓慢,并且很多时候它抛出此错误:错误 R14 内存配额超出(该应用程序托管在赫鲁库)。
缓存此查询的最佳方法是什么?更重要的是,有没有更好的方法来编写这个查询来提高它的速度并避免内存泄漏?
Ps:我一般使用 memcached 来缓存我的应用程序。而且我在其他地方使用过Rails Cache fetch,但是由于它有很多参数,我对如何缓存如此动态的东西感到困惑。
【问题讨论】:
标签: ruby-on-rails performance postgresql activerecord heroku