[英]uploading files to rails 4.0 with paperclip and simple_form
編輯:正如@Justin說的那樣,當我試圖找到一個甚至沒有意識到的解決方案時,我可能搞砸了,oopsy ......將params更改為params.require(:pin).permit(:image,:description)確實解決了它。
雖然它現在不起作用,因為我得到一個“有一個與其內容不匹配的擴展名。
我正在關注一個月的Rails,並嘗試將上傳圖片放入腳手架工作中。 我正在使用paperclip文件和simple_form。 這是我認為相關的代碼(隨意提出要求):
_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來自pins_controller.rb
def pin_params
params.permit(:description, :image)
end
(大多數是我嘗試通過回形針README進行故障排除時)。 每當我上傳文件時,我都會收到錯誤消息
ActionController::ParameterMissing in PinsController#create
param not found: image
如果我嘗試使用params.require的東西我得到一個錯誤,說沒有找到param。 我不知道是什么原因造成的。 如果我刪除pin_params方法,表單字段只返回“不能為空”,無論它們是什么“
這看起來很簡單,但我找不到解決方案
Paperclip具有欺騙驗證,以確保文件的內容實際上與擴展名匹配。 通過使用操作系統的file
命令來確定文件內容,部分地實現了該驗證。 不幸的是,Windows沒有file
命令,因此驗證將始終失敗。
要解決此問題,您應該禁用欺騙。 使用以下代碼創建初始化程序:
module Paperclip
class MediaTypeSpoofDetector
def spoofed?
false
end
end
end
保留validates_attachment_content_type
器是有效的,因為它仍然是限制用戶可以上載的文件類型的最佳方式。 您只需要禁用此驗證的欺騙位。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.