class PostsController < ApplicationController include Pundit before_action :authenticate! def index @site = find_site authorize @site @lang = find_lang(@site) @category = session[:category] = params.dig(:category) @posts = policy_scope(@site.posts_for(@lang), policy_scope_class: PostPolicy::Scope) if params[:sort_by].present? begin @posts.sort_by! do |p| p.send(params[:sort_by].to_s) end rescue ArgumentError end end end def show @site = find_site @lang = find_lang(@site) @post = find_post(@site) end def new @site = find_site @lang = find_lang(@site) @template = find_template(@site) @post = Post.new(site: @site, front_matter: { date: Time.now }, lang: @lang, template: @template) end def create @site = find_site @lang = find_lang(@site) @template = find_template(@site) @post = Post.new(site: @site, lang: @lang, template: @template) @post.update_attributes(repair_nested_params(post_params)) if @post.save redirect_to site_posts_path(@site, lang: @lang) else render 'posts/new' end end def edit @site = find_site @lang = find_lang(@site) @post = find_post(@site) end def update @site = find_site @lang = find_lang(@site) @post = find_post(@site) @post.update_attributes(repair_nested_params(post_params)) if @post.save redirect_to site_posts_path(@site, category: session[:category], lang: @lang) else render 'posts/edit' end end private # Solo permitir cambiar estos atributos de cada articulo 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 obj[key].each {|h| repair_nested_params(h) } end end end end end