app/controllers/panda/cms/admin/posts_controller.rb in panda-cms-0.7.0 vs app/controllers/panda/cms/admin/posts_controller.rb in panda-cms-0.7.2

- old
+ new

@@ -12,11 +12,11 @@ # Get all posts # @type GET # @return ActiveRecord::Collection A list of all posts def index - posts = Panda::CMS::Post.with_user.ordered + posts = Panda::CMS::Post.with_author.ordered render :index, locals: {posts: posts} end # Loads the add post form # @type GET @@ -46,20 +46,16 @@ end # POST /admin/posts def create @post = Panda::CMS::Post.new(post_params) + @post.user_id = current_user.id + @post.content = parse_content(post_params[:content]) # Parse the content before saving - begin - @post.content = JSON.parse(post_params[:content]) - rescue - @post.content = post_params[:content] - end - if @post.save Rails.logger.debug "Post saved successfully" - redirect_to edit_admin_post_path(@post.admin_param), notice: "Post was successfully created." + redirect_to edit_admin_post_path(@post.admin_param), success: "The post was successfully created!" else Rails.logger.debug "Post save failed: #{@post.errors.full_messages.inspect}" flash.now[:error] = @post.errors.full_messages.join(", ") locals = setup_new_post_form(post: @post, preserved_content: post_params[:content]) render :new, locals: locals, status: :unprocessable_entity @@ -67,15 +63,18 @@ end # @type PATCH/PUT # @return def update - Rails.logger.debug "Updating post with params: #{post_params.inspect}" Rails.logger.debug "Current content: #{post.content.inspect}" Rails.logger.debug "New content from params: #{post_params[:content].inspect}" - if post.update(post_params) + # Parse the content before updating + update_params = post_params + update_params[:content] = parse_content(post_params[:content]) + update_params[:user_id] = current_user.id + if post.update(update_params) Rails.logger.debug "Post updated successfully" add_breadcrumb post.title, edit_admin_post_path(post.admin_param) redirect_to edit_admin_post_path(post.admin_param), status: :see_other, flash: {success: "The post was successfully updated!"} @@ -134,12 +133,35 @@ params.require(:post).permit( :title, :slug, :status, :published_at, - :user_id, + :author_id, :content ) + end + + def parse_content(content) + return {} if content.blank? + + begin + # If content is already a hash, return it + return content if content.is_a?(Hash) + + # If it's a string, try to parse it as JSON + parsed = JSON.parse(content) + + # Ensure we have a hash with expected structure + if parsed.is_a?(Hash) && parsed["blocks"].is_a?(Array) + parsed + else + # If structure is invalid, return empty blocks structure + {"blocks" => []} + end + rescue JSON::ParserError => e + Rails.logger.error "Failed to parse post content: #{e.message}" + {"blocks" => []} + end end end end end end