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