From 55b6ff32481b4769a86752815b33334cabc5770a Mon Sep 17 00:00:00 2001 From: cryptogopher Date: Thu, 19 Dec 2024 03:42:28 +0100 Subject: [PATCH] Find successive Unit according to sort order This will allow to insert Units into table without refresh of all items/removal of forms --- app/models/unit.rb | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/app/models/unit.rb b/app/models/unit.rb index c4445b2..073603c 100644 --- a/app/models/unit.rb +++ b/app/models/unit.rb @@ -75,11 +75,16 @@ class Unit < ApplicationRecord .from(units).group(:base_id, :symbol) } scope :ordered, ->{ - left_outer_joins(:base) - .order(arel_table.coalesce(Arel::Table.new(:bases_units)[:symbol], arel_table[:symbol]), - arel_table[:base_id].not_eq(nil), :multiplier, :symbol) + left_outer_joins(:base).order(ordering) } + def self.ordering + [arel_table.coalesce(Arel::Table.new(:bases_units)[:symbol], arel_table[:symbol]), + arel_table[:base_id].not_eq(nil), + :multiplier, + :symbol] + end + before_destroy do # TODO: disallow destruction if any object depends on this unit nil @@ -104,4 +109,14 @@ class Unit < ApplicationRecord Unit.find_or_initialize_by(user: recipient, symbol: symbol) .update!(base: recipient_base, **params) end + + def successive + units = Unit.arel_table + lead = Arel::Nodes::NamedFunction.new('LAG', [units[:id]]) + window = Arel::Nodes::Window.new.order(*Unit.ordering) + lag_id = lead.over(window).as('lag_id') + Unit.with( + units: user.units.left_outer_joins(:base).select(units[Arel.star], lag_id) + ).where(units[:lag_id].eq(id)).first + end end