I am trying to convert a hash to an activerecord relation 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:
Category model:
def top_5_visited
Article.joins(:categories).group('categories.name').sum(:impressions_count)
// Add sort
// Limit to top 5
end
Category controller:
@categories = Category.top_5 visited
A hash {"Simula"=>7, "Haskell"=>5, "JavaScript"=>10, "C#"=>112}
will be created through the following query:
total_count = Article.joins(:categories).group('categories.name').sum(:impressions_count)
I have also tried to convert it to an array using sort_by method:
total_count_sorted = total_count.sort_by {|_key, value| value}
I have googled "convert array to activerecord relation" and referenced this post, but testing this:
Category.where(id: total_count_sort.map(&:id))
in the rails console, brings up this error:
NoMethodError: undefined method id for ["Simula", 7]:Array