Note that there are some explanatory texts on larger screens.

plurals
  1. POPerforming multiple queries on the same model efficiently
    primarykey
    data
    text
    <p>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.</p> <p>Consider the situation where you have a model called <code>Everything</code>. Initially you perform a query which finds those records in <code>Everything</code> which match certain criteria</p> <pre><code>@chosenrecords = Everything.where('name LIKE ?', 'What I want').order('price ASC') </code></pre> <p>I want to remember the contents of <code>@chosenrecords</code> as I will present them to the user as a list, however, I would also like to understand more of the attributes of <code>@chosenrecords</code>,for instance</p> <pre><code>@minimumprice = @chosenrecords.first @numberofrecords = @chosenrecords.count </code></pre> <p>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 <code>Everything</code> model, rather than remembering the records returned in <code>@chosenrecords</code> 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. </p> <p>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.</p> <p>Thanks for your time</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload