简体   繁体   中英

uploading files to rails 4.0 with paperclip and simple_form

Edit: as @Justin said, I probably messed that up when trying to find a solution without even realizing, oopsy... Changing the params to params.require(:pin).permit(:image, :description) did solve it.
Though it doesn't work now because I get a "has an extension that does not match its contents.

I'm following Rails One Month and trying to get upload image into a pins scaffolding working. I'm using paperclip for files, and simple_form. This is the code I think is relevant (feel free to ask for anything):

_pin_form.erb.html

<%= simple_form_for(@pin, :html => {:multipart => true}) do |f| %>
 <%= f.error_notification %>

 <div class="form-inputs">
   <%= f.file_field :image, :label => "Upload an image" %>
   <%= f.input :description, as: :text %>
 </div>

 <div class="form-actions">
   <%= f.button :submit %>
 </div>

pin.rb

class Pin < ActiveRecord::Base

 has_attached_file :image
 belongs_to :user

 validates :description, :presence => true
 validates :user_id, :presence => true
 validates_attachment :image, :presence => true

# Validate content type
 validates_attachment_content_type :image, :content_type => /\Aimage/
# Validate filename
 validates_attachment_file_name :image, :matches => [/png\Z/, /jpe?g\Z/]
# Explicitly do not validate
 do_not_validate_attachment_file_type :image
end

pin_params from pins_controller.rb

def pin_params
  params.permit(:description, :image)
end

(most of these is when I tried troubleshooting through paperclip README). Whenever I upload a file I get an error saying

ActionController::ParameterMissing in PinsController#create
param not found: image

and if I try to use params.require on something I get an error saying param not found. I have no idea what is causing it. If I remove the pin_params method the form fields just return "can't be blank" no matter what's in them"
This seems simple but I just can't find a solution to this

Paperclip has spoofing validation to ensure the contents of the file actually match the extension. This validation is achieved partially by using the file command of the operating system to determine the file content. Unfortunately Windows doesn't have a file command so the validation will always fail.

To workaround this you should disable spoofing. Create an initializer with the following code:

module Paperclip
  class MediaTypeSpoofDetector
    def spoofed?
      false
    end
  end
end

It's valid to leave the validates_attachment_content_type validator though because is it still the best way to restrict the types of files the user is allowed to upload. You just need to disable the spoofing bit of this validation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM