Performing multiple queries on the same model efficiently

ε祈祈猫儿з 提交于 2019-12-08 11:24:12

问题


I've been going round in circles for a few days trying to solve a problem which I've also struggled with in the past. Essentially its an issue of understanding the best (or an efficient) way to perform multiple queries on a model as I'm regularly finding my pages are very slow to load.

Consider the situation where you have a model called Everything. Initially you perform a query which finds those records in Everything which match certain criteria

@chosenrecords = Everything.where('name LIKE ?', 'What I want').order('price ASC')

I want to remember the contents of @chosenrecords as I will present them to the user as a list, however, I would also like to understand more of the attributes of @chosenrecords,for instance

@minimumprice = @chosenrecords.first
@numberofrecords = @chosenrecords.count

When I use the above code in my controller and inspect the command history on the local server, I am surprised to find that each of the three queries involves an SQL query on the original Everything model, rather than remembering the records returned in @chosenrecords and performing the query on that. This seems very inefficient to me and indeed each of the three queries takes the same amount of time to process, making the page perform slowly.

I am more experienced in writing codes in software like MATLAB where once you've calculated the value of a variable it is stored locally and can be quickly interrogated, rather than recalculating that variable on each occasion you want to know more information about it. Please could you guide me as to whether I am just on the wrong track completely and the issues I've identified are just "how it is in Rails" or whether there is something I can do to improve it. I've looked into concepts like using a scope, defining a different variable type, and caching, but I'm not quite sure what I'm doing in each case and keep ending up in a similar hole.

Thanks for your time


回答1:


You are partially on the wrong track. Rails 3 comes with Arel, which defer the query until data is required. In your case, you have generated Arel query but executing it with .first & then with .count. What I have done here is run the first query, get all the results in an array and working on that array in next two lines.

Perform the queries like this:-

@chosenrecords = Everything.where('name LIKE ?', 'What I want').order('price ASC').all

@minimumprice = @chosenrecords.first
@numberofrecords = @chosenrecords.size

It will solve your issue.



来源:https://stackoverflow.com/questions/18811712/performing-multiple-queries-on-the-same-model-efficiently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!