From 1f0bbca87ee52b7a98453ab43e839bef3bfbbff0 Mon Sep 17 00:00:00 2001 From: Sam Date: Thu, 12 Jul 2018 17:59:38 +1000 Subject: [PATCH] FIX: on initial load category subcategories were not mapped correctly --- .../javascripts/discourse/models/site.js.es6 | 24 +++++++++++++++---- test/javascripts/models/site-test.js.es6 | 2 ++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/app/assets/javascripts/discourse/models/site.js.es6 b/app/assets/javascripts/discourse/models/site.js.es6 index 67c9025fe21..f44e92da37a 100644 --- a/app/assets/javascripts/discourse/models/site.js.es6 +++ b/app/assets/javascripts/discourse/models/site.js.es6 @@ -116,14 +116,30 @@ Site.reopenClass(Singleton, { const store = result.store; if (result.categories) { + let subcatMap = {}; + result.categoriesById = {}; - result.categories = _.map( - result.categories, - c => (result.categoriesById[c.id] = store.createRecord("category", c)) - ); + result.categories = _.map(result.categories, c => { + if (c.parent_category_id) { + subcatMap[c.parent_category_id] = + subcatMap[c.parent_category_id] || []; + subcatMap[c.parent_category_id].push(c.id); + } + return (result.categoriesById[c.id] = store.createRecord( + "category", + c + )); + }); // Associate the categories with their parents result.categories.forEach(c => { + let subcategoryIds = subcatMap[c.get("id")]; + if (subcategoryIds) { + c.set( + "subcategories", + subcategoryIds.map(id => result.categoriesById[id]) + ); + } if (c.get("parent_category_id")) { c.set( "parentCategory", diff --git a/test/javascripts/models/site-test.js.es6 b/test/javascripts/models/site-test.js.es6 index d240abe45ba..f18a291b951 100644 --- a/test/javascripts/models/site-test.js.es6 +++ b/test/javascripts/models/site-test.js.es6 @@ -44,6 +44,8 @@ QUnit.test("create categories", assert => { assert.present(parent, "it loaded the parent category"); assert.blank(parent.get("parentCategory"), "it has no parent category"); + assert.equal(parent.get("subcategories").length, 1); + const subcategory = categories.findBy("id", 3456); assert.present(subcategory, "it loaded the subcategory"); assert.equal(