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?
source to share
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
source to share