class Admin::PostsController < Admin::ApplicationController include BlogUrlHelpers include PostViewForAction respond_to :html, :xml, :json before_action :load_blog before_action :find_post, only: [:edit, :update, :destroy] around_action :create_redirect_if_necessary, only: :update def index @posts = SpudPost.for_blog(params[:blog_key]).ordered.paginate(page: params[:page], per_page: 15) @posts = @posts.search(params[:search]) if params[:search] respond_with @posts end def edit respond_with @post end def show end def update if @post.update_attributes(post_params) flash[:notice] = 'Post was successfully updated.' end respond_with @post, location: admin_posts_path end def new @post = SpudPost.new(published_at: Time.zone.now, spud_user_id: current_user.id) respond_with @post end def create @post = SpudPost.new(post_params) @post.blog_key = params[:blog_key] flash[:notice] = 'Post was successfully created.' if @post.save respond_with @post, location: admin_posts_path end def destroy flash[:notice] = 'Post was successfully deleted.' if @post.destroy respond_with @post, location: admin_posts_path end def preview @post = if params[:post_id] SpudPost.find_by!(id: params[:post_id]) else SpudPost.new end @post.assign_attributes(post_params) render template: post_view_for_action(:show), controller: :posts, layout: @config.layout end def render_preview render template: post_view_for_action(:show), controller: :posts, layout: @config.layout end private def find_post @post = SpudPost.find(params[:id]) if @post.blank? flash[:error] = 'Post not found!' redirect_to(admin_posts_path) && (return false) end end def post_params permitted = [:published_at, :title, :content, :spud_user_id, :url_name, :visible, :comments_enabled, :meta_keywords, :meta_description, :content_format, :custom_author, category_ids: []] if Spud::Blog.permitted_attributes.present? permitted += Spud::Blog.permitted_attributes end p = params.require(:spud_post).permit(permitted) p[:updated_at] = DateTime.now return p end def load_blog @config = SpudBlogConfig.find(params[:blog_key]) if @config.blank? redirect_to admin_root_path return false else act_as_app "#{@config.name} Posts".parameterize.underscore.to_sym add_breadcrumb "#{@config.name} Posts", admin_posts_path(blog_key: @config.key) end end # Create a redirect if the post URL has changed # # Normally this sort of thing might belong in a model after_update hook, but the model # layer has no knowledge of URL helpers. # def create_redirect_if_necessary @_redirect_source = post_path(@post.url_name, blog_key: @post.blog_key, only_path: true) yield ensure if @post.errors.empty? @_redirect_destination = post_path(@post.url_name, blog_key: @post.blog_key, only_path: true) if @_redirect_source != @_redirect_destination TbRedirect.create_smart(source: @_redirect_source, destination: @_redirect_destination, created_by: 'blog', owner: @post) end end end end