From 276d9281cf07a2ee8c368acb9ba43ed2d80a8e95 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 2 Apr 2021 08:48:57 +0300 Subject: [PATCH] Fixes #3490 - Error 500:{"error":"undefined method `+' for nil:NilClass"} - Creating Overview --- app/models/overview.rb | 10 +++++++++- spec/models/overview_spec.rb | 22 ++++++++++++++++++---- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/app/models/overview.rb b/app/models/overview.rb index 98b0d6ec3..d3f119b5f 100644 --- a/app/models/overview.rb +++ b/app/models/overview.rb @@ -19,6 +19,14 @@ class Overview < ApplicationModel before_create :fill_link_on_create, :fill_prio before_update :fill_link_on_update, :rearrangement + def self.calculate_prio + existing_maximum = Overview.maximum(:prio) + + return 0 if !existing_maximum + + existing_maximum + 1 + end + private def rearrangement @@ -63,7 +71,7 @@ class Overview < ApplicationModel def fill_prio return true if prio.present? - self.prio = Overview.maximum(:prio) + 1 + self.prio = self.class.calculate_prio true end diff --git a/spec/models/overview_spec.rb b/spec/models/overview_spec.rb index 8522f392e..081f6235b 100644 --- a/spec/models/overview_spec.rb +++ b/spec/models/overview_spec.rb @@ -75,18 +75,32 @@ RSpec.describe Overview, type: :model do end describe '#fill_prio' do + before do + described_class.destroy_all + end it 'fill an empty prio with the maximum prio plus one' do - overview1 = create(:overview, prio: 1) overview2 = create(:overview, prio: 200) overview3 = create(:overview, prio: nil) overviews = described_class.all.order(prio: :asc).pluck(:id) - expect(overviews.first).to eq(overview1.id) - expect(overviews.second).to eq(overview2.id) - expect(overviews.last).to eq(overview3.id) + expect(overviews).to eq [overview1.id, overview2.id, overview3.id] + end + + it 'sets first Overview priority as 0' do + overview = create :overview, prio: nil + + expect(overview.prio).to be 0 + end + + it 'sets new Overview priority as +1' do + create :overview, prio: 123 + + overview_next = create :overview, prio: nil + + expect(overview_next.prio).to be 124 end end end