# Sort Categories by name

**URL:** <https://meta.discourse.org/t/sort-categories-by-name/62764>\
**Category:** Development\
**Created:** [2017 年 5 月 15 日午後 11:47 UTC](https://meta.discourse.org/t/sort-categories-by-name/62764 "2017-05-15T23:47:35Z")\
**Posts on this page:** 1\
**Showing post:** 2

<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:** [2017 年 5 月 16 日午前 12:13 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 😉

---

_[View the full topic](https://meta.discourse.org/t/sort-categories-by-name/62764)._
