From 747a8a93577aa89e3900cfb52790bb7e2672dc84 Mon Sep 17 00:00:00 2001 From: cryptogopher Date: Fri, 8 May 2026 22:09:37 +0200 Subject: [PATCH] Fix SQLite query compatibility inside WITH clause SQLite3::SQLException: circular reference --- app/models/unit.rb | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/app/models/unit.rb b/app/models/unit.rb index 18ef123..8232e60 100644 --- a/app/models/unit.rb +++ b/app/models/unit.rb @@ -77,16 +77,14 @@ class Unit < ApplicationRecord .from(units).group(:base_id, :symbol) } scope :ordered, ->{ - left_outer_joins(:base).order(ordering) + left_outer_joins(:base).order([ + arel_table.coalesce(Arel::Table.new(:bases_units)[:symbol], arel_table[:symbol]), + arel_table[:base_id].not_eq(nil), + arel_table[:multiplier], + arel_table[:symbol] + ]) } - 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 @@ -114,11 +112,10 @@ class Unit < ApplicationRecord 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 + Unit.with(units_with_lag: user.units.ordered.select( + units[Arel.star], + Arel::Nodes::NamedFunction.new('LAG', [units[:id]]).over.as('lag_id') + )).from(Arel::Table.new(:units_with_lag).as(:units)) + .where(units[:lag_id].eq(id)).first end end