diff --git a/app/controllers/quantities_controller.rb b/app/controllers/quantities_controller.rb index fd7f667..c53c890 100644 --- a/app/controllers/quantities_controller.rb +++ b/app/controllers/quantities_controller.rb @@ -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 diff --git a/app/models/quantity.rb b/app/models/quantity.rb index 62e59c4..c88f301 100644 --- a/app/models/quantity.rb +++ b/app/models/quantity.rb @@ -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 diff --git a/app/views/quantities/update.turbo_stream.erb b/app/views/quantities/update.turbo_stream.erb index ea880c8..b94fd49 100644 --- a/app/views/quantities/update.turbo_stream.erb +++ b/app/views/quantities/update.turbo_stream.erb @@ -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 %>