The discussion revolves around sorting subcategories in a category by name in Discourse. pfaffman initially seeks a solution, providing an example code. david proposes a revised approach using Ruby, sorting categories and their children by name and assigning their position alphabetically.
david’s solution is implemented by pfaffman to create a method sort_matching_subcategories(search) that finds categories matching a search term, sorts them by name, and recursively sorts their subcategories.
I am by no means a ruby expert, but I think this is a sensible way:
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
This will find all categories that match search and sort them and the subcategories that they contain.
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