diff --git a/app/services/post_service.rb b/app/services/post_service.rb index 1d7e1a99..c82953e3 100644 --- a/app/services/post_service.rb +++ b/app/services/post_service.rb @@ -195,9 +195,7 @@ PostService = Struct.new(:site, :usuarie, :post, :params, keyword_init: true) do case metadata.type when 'has_and_belongs_to_many' associated_posts(value_was - value).each do |remove_post| - remove_post[inverse_attribute].value.delete(post.uuid.value) - - associated_posts_to_save << remove_post + remove_relation_from(remove_post[inverse_attribute], post.uuid.value) end associated_posts(value - value_was).each do |add_post| @@ -208,17 +206,12 @@ PostService = Struct.new(:site, :usuarie, :post, :params, keyword_init: true) do end when 'has_many' associated_posts(value_was - value).each do |remove_post| - # @todo por qué no podemos usar nil para deshabilitar un valor? - remove_post[inverse_attribute].value = '' - - associated_posts_to_save << remove_post + remove_relation_from(remove_post[inverse_attribute], '') end associated_posts(value - value_was).each do |add_post| associated_posts(add_post[inverse_attribute].value_was).each do |remove_post| - remove_post[attribute].value.delete(add_post.uuid.value) - - associated_posts_to_save << remove_post + remove_relation_from(remove_post[attribute], add_post.uuid.value) end add_post[inverse_attribute].value = post.uuid.value @@ -228,9 +221,7 @@ PostService = Struct.new(:site, :usuarie, :post, :params, keyword_init: true) do when 'belongs_to' if value_was.present? associated_posts(value_was).each do |remove_post| - remove_post[inverse_attribute].value.delete(value_was) - - associated_posts_to_save << remove_post + remove_relation_from(remove_post[inverse_attribute], value_was) end end @@ -244,4 +235,15 @@ PostService = Struct.new(:site, :usuarie, :post, :params, keyword_init: true) do end end end + + # @todo por qué no podemos usar nil para deshabilitar un valor? + def remove_relation_from(metadata, value) + case metadata.value + when Array then metadata.value.delete(value) + when String then metadata.value = '' + end + + associated_posts_to_save << metadata.post + nil + end end