Don't error when deleting supplier/group with already existing deleted name (closes foodcoops/foodsoft#197)

This commit is contained in:
wvengen 2015-04-17 20:05:46 +02:00
parent b028431bf0
commit 17cbc57850
3 changed files with 33 additions and 3 deletions

View File

@ -0,0 +1,25 @@
module MarkAsDeletedWithName
extend ActiveSupport::Concern
def mark_as_deleted
# get maximum length of name
max_length = 100000
if lenval = self.class.validators_on(:name).detect { |v| v.is_a?(ActiveModel::Validations::LengthValidator) }
max_length = lenval.options[:maximum]
end
# find unique deleted name
# (would have been nice to use retry, but there is no general duplicate-entry exception)
n = ''
begin
append = ' \u2020' + n
deleted_name = name.truncate(max_length-append.length, omission: '') + append
if n.blank?
n = 'A'
else
n.succ!
end
end while self.class.where(name: deleted_name).exists?
# mark as deleted
update_columns deleted_at: Time.now, name: deleted_name
end
end

View File

@ -1,6 +1,9 @@
# encoding: utf-8
# Groups organize the User.
# A Member gets the roles from the Group
class Group < ActiveRecord::Base
include MarkAsDeletedWithName
has_many :memberships, dependent: :destroy
has_many :users, :through => :memberships
@ -32,8 +35,8 @@ class Group < ActiveRecord::Base
# TODO: Checks for participating in not closed orders
transaction do
memberships.destroy_all
# TODO: What should happen to users?
update_column :deleted_at, Time.now
# @todo what should happen to the users?
super
end
end
end

View File

@ -1,5 +1,7 @@
# encoding: utf-8
class Supplier < ActiveRecord::Base
include MarkAsDeletedWithName
has_many :articles, -> { where(:type => nil).includes(:article_category).order('article_categories.name', 'articles.name') }
has_many :stock_articles, -> { includes(:article_category).order('article_categories.name', 'articles.name') }
has_many :orders
@ -109,7 +111,7 @@ class Supplier < ActiveRecord::Base
def mark_as_deleted
transaction do
update_column :deleted_at, Time.now
super
articles.each(&:mark_as_deleted)
end
end