title: Ruby: Convert an array or hash to an activerecord relation
body: <p>I am trying to <strong>convert a hash to an activerecord relation</strong> but am not able to do so. I intend to use the activerecord relation to sort and then filter the Category table. The end goal is to  create an instance method to filter the top 5 visited categories, which i can then use/call in the controller. This is what i have in mind:</p>
  
  <p><strong>Category model:</strong></p>
  
  <pre><code>def top_5_visited
          Article.joins(:categories).group('categories.name').sum(:impressions_count)
  // Add sort
  // Limit to top 5 
  end
  </code></pre>
  
  <p><strong>Category controller:</strong></p>
  
  <pre><code>@categories = Category.top_5 visited
  </code></pre>
  
  <p>A <strong>hash</strong> <code>{"Simula"=&gt;7, "Haskell"=&gt;5, "JavaScript"=&gt;10, "C#"=&gt;112}</code> will be created through the following query:</p>
  
  <pre><code>total_count = Article.joins(:categories).group('categories.name').sum(:impressions_count)
  </code></pre>
  
  <p>I have also tried to convert it to an array using sort_by method:</p>
  
  <pre><code>total_count_sorted = total_count.sort_by {|_key, value| value}
  </code></pre>
  
  <p>I have googled "convert array to activerecord relation" and referenced <a href="https://stackoverflow.com/questions/17331862/converting-an-array-of-objects-to-activerecordrelation">this</a> post, but testing this: </p>
  
  <pre><code>Category.where(id: total_count_sort.map(&amp;:id))
  </code></pre>
  
  <p>in the rails console, brings up this error: </p>
  
  <blockquote>
    <p>NoMethodError: undefined method id for ["Simula", 7]:Array</p>
  </blockquote>