Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I combine results from two queries on the same model?
    text
    copied!<p>I need to return exactly ten records for use in a view. I have a highly restrictive query I'd like to use, but I want a less restrictive query in place to fill in the results in case the first query doesn't yield ten results.</p> <p>Just playing around for a few minutes, and this is what I came up with, but it doesn't work. I think it doesn't work because merge is meant for combining queries on different models, but I could be wrong.</p> <pre><code>class Article &lt; ActiveRecord::Base ... def self.listed_articles Article.published.order('created_at DESC').limit(25).where('listed = ?', true) end def self.rescue_articles Article.published.order('created_at DESC').where('listed != ?', true).limit(10) end def self.current Article.rescue_articles.merge(Article.listed_articles).limit(10) end ... end </code></pre> <p>Looking in console, this forces the restrictions in listed_articles on the query in rescue_articles, showing something like:</p> <pre><code>Article Load (0.2ms) SELECT `articles`.* FROM `articles` WHERE (published = 1) AND (listed = 1) AND (listed != 1) ORDER BY created_at DESC LIMIT 4 Article Load (0.2ms) SELECT `articles`.* FROM `articles` WHERE (published = 1) AND (listed = 1) AND (listed != 1) ORDER BY created_at DESC LIMIT 6 OFFSET 4 </code></pre> <p>I'm sure there's some ridiculously easy method I'm missing in the documentation, but I haven't found it yet.</p> <p>EDIT: What I want to do is return all the articles where listed is true out of the twenty-five most recent articles. If that doesn't get me ten articles, I'd like to add enough articles from the most recent articles where listed is not true to get my full ten articles.</p> <p>EDIT #2: In other words, the merge method seems to string the queries together to make one long query instead of merging the results. I need the top ten results of the two queries (prioritizing listed articles), not one long query.</p>
 

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