Don't duplicate ancestors search in #successive

This commit is contained in:
cryptogopher 2025-01-12 18:11:37 +01:00
parent 421515e5ce
commit 17b4e4f8a7
2 changed files with 5 additions and 15 deletions

View File

@ -19,7 +19,8 @@ class QuantitiesController < ApplicationController
def create
@quantity = current_user.quantities.new(quantity_params)
if @quantity.save
@before, @quantity, @ancestors = @quantity.succ_and_ancestors
@before = @quantity.successive
@ancestors = @quantity.ancestors
flash.now[:notice] = t('.success', quantity: @quantity)
else
render :new

View File

@ -66,25 +66,14 @@ class Quantity < ApplicationRecord
# Return: self, ancestors and successive record in order of appearance,
# including :depth attribute. Used for partial view reload.
def succ_and_ancestors
def successive
quantities = Quantity.arel_table
ancestors = Arel::Table.new('ancestors')
Quantity.with(
ancestors: user.quantities.ordered.select(
quantities: user.quantities.ordered.select(
Arel::Nodes::NamedFunction.new('LAG', [quantities[:id]]).over.as('lag_id')
)
)
.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]).to_a
.then do |records|
[records.last == self ? nil : records.pop, records.pop, records]
end
).where(quantities[:lag_id].eq(id)).first
end
# Return: ancestors of (possibly destroyed) self; include depths, also on