From 586f4c58248d8067dcaca7b42f4342e89fa100c0 Mon Sep 17 00:00:00 2001 From: f Date: Tue, 24 Jul 2018 17:49:32 -0300 Subject: [PATCH] asegurarse que guardamos todo como objectos naturales de ruby --- app/controllers/posts_controller.rb | 18 ++++++++++++++++-- app/models/post.rb | 14 ++++++++------ 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb index c26d3952..480f6007 100644 --- a/app/controllers/posts_controller.rb +++ b/app/controllers/posts_controller.rb @@ -54,8 +54,7 @@ class PostsController < ApplicationController @site = find_site @lang = find_lang(@site) @post = find_post(@site) - - @post.update_attributes(post_params) + @post.update_attributes(repair_nested_params(post_params)) if @post.save redirect_to site_posts_path(@site, category: session[:category], lang: @lang) @@ -70,4 +69,19 @@ class PostsController < ApplicationController def post_params params.require(:post).permit(@post.template_params) end + + # https://gist.github.com/bloudermilk/2884947#gistcomment-1915521 + def repair_nested_params(obj) + obj.each do |key, value| + if value.is_a?(ActionController::Parameters) || value.is_a?(Hash) + # If any non-integer keys + if value.keys.find {|k, _| k =~ /\D/ } + repair_nested_params(value) + else + obj[key] = value.values + value.values.each {|h| repair_nested_params(h) } + end + end + end + end end diff --git a/app/models/post.rb b/app/models/post.rb index 52bc4fc1..fc183820 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -196,12 +196,10 @@ class Post # imita Model.update_attributes de ActiveRecord def update_attributes(attrs) - # el cuerpo se maneja por separado - @content = attrs.delete('content') if attrs.key? 'content' # convertir los hashes en arrays si los campos son anidados - # usamos to_h por todos lados porque sino son + # usamos to_hash por todos lados porque sino son # HashWithIndifferentAccess - attrs = attrs.to_h.map do |k,v| + _attrs = attrs.to_hash.map do |k,v| t = template_fields.find { |t| t.key == k } if t # Subir la imagen! @@ -224,14 +222,17 @@ class Post end if t.nested? - v = t.array? ? v.values.map(&:to_h) : v.to_h + v = t.array? ? v.map(&:to_hash) : v.to_hash end end { k => v } end.reduce(Hash.new, :merge).stringify_keys - merge_with_front_matter! attrs + # el cuerpo se maneja por separado + @content = _attrs.delete('content') if _attrs.key? 'content' + + merge_with_front_matter! _attrs end # Requisitos para que el post sea válido @@ -306,6 +307,7 @@ class Post end end + # TODO convertir a hash para que sea más fácil buscar uno def template_fields return [] unless template @template_fields ||= template.front_matter.map do |key, contents|