ancestors() sets depth for self, instead of returning new instance

This commit is contained in:
cryptogopher 2025-01-12 18:09:34 +01:00
parent d5e7ccacf5
commit 421515e5ce
3 changed files with 10 additions and 4 deletions

View File

@ -31,7 +31,7 @@ class QuantitiesController < ApplicationController
def update
if @quantity.update(quantity_params.except(:parent_id))
@ancestors = @quantity.ancestors(include_self: true)
@ancestors = @quantity.ancestors
flash.now[:notice] = t('.success', quantity: @quantity)
else
render :edit

View File

@ -13,6 +13,9 @@ class Quantity < ApplicationRecord
length: {maximum: type_for_attribute(:name).limit}
validates :description, length: {maximum: type_for_attribute(:description).limit}
# Not persisted attribute
attribute :depth, :integer
scope :defaults, ->{ where(user: nil) }
scope :ordered, ->{
numbered = Arel::Table.new('numbered')
@ -84,7 +87,9 @@ class Quantity < ApplicationRecord
end
end
def ancestors(include_self: false)
# Return: ancestors of (possibly destroyed) self; include depths, also on
# self (unless destroyed)
def ancestors
quantities = Quantity.arel_table
ancestors = Arel::Table.new('ancestors')
@ -93,13 +98,14 @@ class Quantity < ApplicationRecord
# amount needed to set biggest negative depth to 0.
Quantity.with_recursive(ancestors: [
user.quantities.select(quantities[Arel.star], Arel::Nodes.build_quoted(0).as('depth'))
.where(id: include_self ? id : parent_id),
.where(id: parent_id),
user.quantities.select(quantities[Arel.star], ancestors[:depth] - 1)
.joins(quantities.create_join(
ancestors, quantities.create_on(quantities[:id].eq(ancestors[:parent_id]))
))
]).select(ancestors[Arel.star]).from(ancestors).to_a.then do |records|
records.map(&:depth).min&.abs.then do |maxdepth|
self.depth = (maxdepth || -1) + 1 unless frozen?
records.each { |r| r.depth += maxdepth }
end
end

View File

@ -1,4 +1,4 @@
<%= turbo_stream.close_form dom_id(@quantity, :edit) %>
<% @ancestors.map do |ancestor| %>
<% @ancestors.push(@quantity).map do |ancestor| %>
<%= turbo_stream.replace ancestor %>
<% end %>