uploading files to rails 4.0 with paperclip and simple_form

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

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

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!