jesica
jesica

Reputation: 685

How to make order in group_by records query in rails

This is my current code

cat = Category.select(:id, :name, :parent, :jobs_count).group_by{|p| p.parent}

cat.each do |parent, childs|
   = parent
   childs.each do |name|
     = name.name
   end
end

the results of this are,

Technology (The parent)

Now I want to order childs records by jobs_count, I am trying to do it using the code below,

childs.order(jobs_count: :desc).each do |name|
Error:
=> undefined method `order' for #<Array:0x007f11cc08a2c0>

also like that into main query

Category.select(:id, :name, :parent, :jobs_count).group_by{|p| p.parent}.order(jobs_count: :desc)
Error:
#=> undefined method `order' for #<Array:0x007f11cc242e50>

It not working for me, how can I order the records by jobs_count

Upvotes: 2

Views: 338

Answers (1)

fool-dev
fool-dev

Reputation: 7777

You can be using sort_by method like on the childs.each block like the following

childs.sort_by{|j| - j.jobs_count }.each do |name|

So the full code is:

cat.each do |parent, childs|
   = parent
   childs.sort_by{|j| - j.jobs_count }.each do |name|
     = name.name
   end
end

It should work.

Upvotes: 3

Related Questions