0

I am new to rails and have been following a tutorial on YouTube https://www.youtube.com/watch?v=70Pu_28yvdI and have gotten to around minute 40 and when I try to create a new post and attach an image I get an error Image has an extension that does not match its content, I coded the exact same code he did and keep getting the error. Thank you so much for the help.

post.rb file

class Post < ActiveRecord::Base
    belongs_to  :user
    has_attached_file :image, styles: { medium: "700x500#", small: "350x250" }
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end

post_controller.rb file

class PostsController < ApplicationController
    before_action :find_post, only: [:show, :edit, :update, :destroy]
    before_action :authenticate_user!, except: [:index, :show]

    def index
        @post = Post.all.order("created_at DESC")   
    end

    def show
    end

    def new
        @post = current_user.posts.build
    end

    def create
        @post = current_user.posts.build(post_params)
        if @post.save
            redirect_to @post
        else
            render 'new'
        end 
    end

    def edit    
    end

    def update
        if @post.update(post_params)
            redirect_to @post
        else
            render 'edit'
        end 
    end

    def destroy
        @post.destroy
        redirect_to root_path   
    end

    private

    def find_post
        @post = Post.find(params[:id])
    end

    def post_params
        params.require(:post).permit(:title, :link, :description, :image)
    end

end

20150728130528_add_attachment_image_to_posts.rb file

class AddAttachmentImageToPosts < ActiveRecord::Migration
  def self.up
    change_table :posts do |t|
      t.attachment :image
    end
  end

  def self.down
    remove_attachment :posts, :image
  end
end

1 Answers1

0

If you're on windows(from https://github.com/thoughtbot/paperclip):

If you're using Windows 7+ as a development environment, you may need to install the file.exe application manually. The file spoofing system in Paperclip 4+ relies on this; if you don't have it working, you'll receive Validation failed: Upload file has an extension that does not match its contents. errors.

Make sure you're using the same image type as you are validating:

You should ensure that you validate files to be only those MIME types you explicitly want to support. If you don't, you could be open to XSS attacks if a user uploads a file with a malicious HTML payload.

If you're only interested in images, restrict your allowed content_types to image-y ones:

validates_attachment :avatar,
      :content_type => { :content_type => ["image/jpeg", "image/gif", "image/png"] }

Paperclip::ContentTypeDetector will attempt to match a file's extension to an inferred content_type, regardless of the actual contents of the file.

LanceH
  • 1,726
  • 13
  • 20