From 1e7ef75e8b45e641d20c6a0571062afce696fc28 Mon Sep 17 00:00:00 2001 From: cryptogopher Date: Thu, 9 Jan 2025 15:59:18 +0100 Subject: [PATCH] Include self and ancestors in result --- app/models/quantity.rb | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/app/models/quantity.rb b/app/models/quantity.rb index f7dce76..d62b815 100644 --- a/app/models/quantity.rb +++ b/app/models/quantity.rb @@ -58,12 +58,23 @@ class Quantity < ApplicationRecord parent_id.nil? end + # Return: record, its ancestors and succesive record in order of appearance, + # including :depth attribute. Used for table view reload. def successive quantities = Quantity.arel_table + ancestors = Arel::Table.new('ancestors') Quantity.with( - quantities: user.quantities.ordered.select( + ancestors: user.quantities.ordered.select( Arel::Nodes::NamedFunction.new('LAG', [quantities[:id]]).over.as('lag_id') ) - ).where(quantities[:lag_id].eq(id)).first + ) + .with_recursive(quantities: [ + Arel::SelectManager.new.project(ancestors[Arel.star]).from(ancestors) + .where(ancestors[:id].eq(id).or(ancestors[:lag_id].eq(id))), + Arel::SelectManager.new.project(ancestors[Arel.star]).from(ancestors) + .join(quantities).on(quantities[:parent_id].eq(ancestors[:id])) + .where(quantities[:lag_id].not_eq(id)) + ]).order(quantities[:path]) + # return: .first == self ? nul, ancestors : ancestors.pop, ancestors end end