The rails are grouped in order and order

In my controller, I get all the add-ons grouped by category:

def index
  @categories = Extra.all.group_by(&:category)
end

      

The result is something like an array of hashes:

{#<Category id:1, sort:2> => [#<Extra id:1>,#<Extra id:2],
 #<Category id:2, sort: 1> => [#<Extra id:3>,#<Extra id:4>]}

      

I want to sort by column "sort" instead of id, which should look like this:

{#<Category id:2, sort:1> => [#<Extra id:3>,#<Extra id:4],
 #<Category id:1, sort: 2> => [#<Extra id:1>,#<Extra id:2>]}

      

When I try:

def index
  @categories = Extra.all.group_by(&:category).sort_by{|s| s[:sort]}
end

      

I am getting "implicit character to integer conversion". Is it because I used the character in sort_by?

+3


source to share


2 answers


Try it, group_by

will return you hash

and you are trying to call [:sort]

on the array[#<Category id:2, sort:1>, [#<Extra id:3>,#<Extra id:4]]

You have to take them in two variables |key, value|

and the key will becategory



def index
  @categories = Extra.all.group_by(&:category).sort_by{|category, _extras| category.sort }
end

      

+4


source


Use the method order

to sort on the database:



@categories = Extra.order(sort: :asc).group_by(&:category)

      

+1


source







All Articles