diff --git a/app/models/metadata_template.rb b/app/models/metadata_template.rb index 03d42339..5af68099 100644 --- a/app/models/metadata_template.rb +++ b/app/models/metadata_template.rb @@ -12,6 +12,10 @@ MetadataTemplate = Struct.new(:site, :document, :name, :label, :type, false end + def nested? + false + end + def inspect "#<#{self.class} site=#{site.name.inspect} post=#{post.id.inspect} value=#{value.inspect}>" end diff --git a/app/models/post.rb b/app/models/post.rb index 60382baf..953598a9 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -423,6 +423,13 @@ class Post @usuaries ||= document_usuaries.empty? ? [] : Usuarie.where(id: document_usuaries).to_a end + # Todos los atributos anidados + # + # @return [Array] + def nested_attributes + @nested_attributes ||= attributes.map { |a| self[a] }.select(&:nested?).map(&:name) + end + private # Levanta un error si al construir el artículo no pasamos un atributo. diff --git a/app/services/post_service.rb b/app/services/post_service.rb index 20256d68..08a46ae7 100644 --- a/app/services/post_service.rb +++ b/app/services/post_service.rb @@ -17,6 +17,8 @@ PostService = Struct.new(:site, :usuarie, :post, :params, keyword_init: true) do post.slug.value = p[:slug] if p[:slug].present? end + # Crea los posts anidados + create_nested_posts! post, params[:post] update_related_posts commit(action: :created, add: files) if post.save @@ -122,7 +124,7 @@ PostService = Struct.new(:site, :usuarie, :post, :params, keyword_init: true) do # Solo permitir cambiar estos atributos de cada articulo def post_params - params.require(:post).permit(post.params) + @post_params ||= params.require(:post).permit(post.params).to_h end # Eliminar metadatos internos @@ -173,4 +175,20 @@ PostService = Struct.new(:site, :usuarie, :post, :params, keyword_init: true) do site.update licencia: Licencia.find_by_icons('custom') end end + + # Encuentra todos los posts anidados y los crea o modifica + def create_nested_posts!(post, params) + post.nested_attributes.each do |nested_attribute| + nested_metadata = post[nested_attribute] + # @todo find_or_initialize + nested_post = site.posts(lang: post.lang.value).build(layout: nested_metadata.nested) + nested_params = params.require(nested_attribute).permit(nested_post.params).to_hash + + # Completa la relación 1:1 + nested_params[nested_metadata.inverse.to_s] = post.uuid.value + post[nested_attribute].value = nested_post.uuid.value + + files << nested_post.path.absolute if nested_post.update(nested_params) + end + end end