# Sort Categories by name

**URL:** https://meta.discourse.org/t/sort-categories-by-name/62764
**Category:** Development
**Created:** [May 15, 2017, 11:47pm UTC](https://meta.discourse.org/t/sort-categories-by-name/62764 "2017-05-15T23:47:35Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![pfaffman](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/pfaffman/32/120154_2.png) [@pfaffman](https://meta.discourse.org/u/pfaffman)
#### Post date: [May 15, 2017, 11:47pm UTC](https://meta.discourse.org/t/sort-categories-by-name/62764/1 "2017-05-15T23:47:35Z")

</div>

I need to sort all of the subcategories in a category by name.

Something like

```plaintext
cats = Category.find_by_sql("select * from categories where name like '%whatever%')
x=0
cats.sort_by_name.each do |c|
   x += 1
   c.position = x
end

```

is there some Discourse way or should I just be asking at StackOverflow?

---

<div class="post-metadata">

### Author: ![david](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/david/32/157490_2.png) [@david](https://meta.discourse.org/u/david)
#### Post date: [May 16, 2017, 12:13am UTC](https://meta.discourse.org/t/sort-categories-by-name/62764/2 "2017-05-16T00:13:55Z")

</div>

I am by no means a ruby expert, but I think this is a sensible way:

```ruby
parent_category = Category.where(:name=>"Whatever").first

children = Category.where(:parent_category_id=>parent_category.id)

x = 0
children.order(:name).each do |c|
   puts c.name
   x += 1
   c.position = x
   c.save!()
end;

```

that’ll output the name of each of the children of parent\_category, and assign their position alphabetically.

I tried it on the console and it worked - but I provide no guarentee it won’t cause your server to set on fire or similar 😉

---

<div class="post-metadata">

### Author: ![pfaffman](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/pfaffman/32/120154_2.png) [@pfaffman](https://meta.discourse.org/u/pfaffman)
#### Post date: [May 16, 2017, 6:00pm UTC](https://meta.discourse.org/t/sort-categories-by-name/62764/3 "2017-05-16T18:00:39Z")

</div>

Thanks, @david! That was a huge help.

This will find all categories that match `search` and sort them and the subcategories that they contain.

```ruby
  def sort_matching_subcategories(search)
    categories = Category.where("name like ?", search)
    position = 100
    categories.order(:name).each do |cat|
      position += 1
      cat.position = position
      cat.save!()
      c_position = 0
      children = Category.where(:parent_category_id=>cat.id)
      children.order(:name).each do |c|
        c_position += 1
        c.position = c_position
        c.save!()
      end
    end
  end

```
