diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rb index 54f9aa68..074283e6 100644 --- a/app/controllers/categories_controller.rb +++ b/app/controllers/categories_controller.rb @@ -7,7 +7,18 @@ def show end def subcategories - categories = Category.where("id in (select child_id from category_relationships where parent_id=?)", params[:id]) + # Fetch category children records. Records are ordered by (optional) child_priority_rank + category_relationships = CategoryRelationship.where(parent_id: params[:id]) + .order(:child_priority_rank) + .select(:child_id, :child_priority_rank) + + child_ids = category_relationships.pluck(:child_id) + + # Query categories using child_ids and order by child_priority_rank + categories = Category.joins("INNER JOIN (#{category_relationships.to_sql}) cr ON categories.id = cr.child_id") + .where(id: child_ids) + .order("cr.child_priority_rank") + render json: CategoryPresenter.present(categories) end diff --git a/db/migrate/20230609201040_add_child_priority_rank_column_to_category_relationships.rb b/db/migrate/20230609201040_add_child_priority_rank_column_to_category_relationships.rb new file mode 100644 index 00000000..106ab8b5 --- /dev/null +++ b/db/migrate/20230609201040_add_child_priority_rank_column_to_category_relationships.rb @@ -0,0 +1,6 @@ +class AddChildPriorityRankColumnToCategoryRelationships < ActiveRecord::Migration[6.1] + def change + add_column :category_relationships, :child_priority_rank, :integer + add_index(:category_relationships, [:child_id, :parent_id], :unique => true) + end +end diff --git a/db/schema.rb b/db/schema.rb index 26eff2f0..9f951364 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2023_05_30_212331) do +ActiveRecord::Schema.define(version: 2023_06_09_201040) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -117,6 +117,8 @@ create_table "category_relationships", id: false, force: :cascade do |t| t.integer "parent_id", null: false t.integer "child_id", null: false + t.integer "child_priority_rank" + t.index ["child_id", "parent_id"], name: "index_category_relationships_on_child_id_and_parent_id", unique: true end create_table "change_requests", force: :cascade do |t|