Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails group by and order by column

In my controller I'm getting all Extras 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 category "sort" column 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 get "no implicit conversion of Symbol into Integer". Is that because I used a symbol in the "sort_by"?

like image 470
Daniel Sousa Avatar asked May 25 '17 11:05

Daniel Sousa


2 Answers

Try this, group_by will return you hash and you are trying to call [:sort] on an Array of [#<Category id:2, sort:1>, [#<Extra id:3>,#<Extra id:4]]

You should take them in two variables |key, value| and the key will be category

def index
  @categories = Extra.all.group_by(&:category).sort_by{|category, _extras| category.sort }
end
like image 101
Deepak Mahakale Avatar answered Sep 28 '22 09:09

Deepak Mahakale


Use the order method to do the sorting at the database:

@categories = Extra.order(sort: :asc).group_by(&:category)
like image 39
user000001 Avatar answered Sep 28 '22 09:09

user000001