我正在尝试使用paperclip将pdf文件上传到rails应用程序。我可以获取表单上传元素,但是当我去提交时,我收到以下错误:
2 errors prohibited this asset from being saved: Uploaded file can't
be empty Uploaded file file name can't be empty
相关代码:
型号:
class Asset < ActiveRecord::Base
belongs_to :course
#set up "uploaded_file" field as attached_file (using Paperclip)
has_attached_file :uploaded_file
validates_attachment_size :uploaded_file, :less_than => 20.megabytes
validates_attachment_presence :uploaded_file
end
控制器:
class AssetsController < ApplicationController
before_action :set_asset, only: [:show, :edit, :update, :destroy]
respond_to :html
def index
@assets = Assets.all
respond_with(@assets)
end
def show
respond_with(@asset)
end
def new
@asset = Asset.new
respond_with(@asset)
end
def edit
@asset = Assets.find(:params[:id])
end
def create
@asset = Asset.new(asset_params)
@asset.save
respond_with(@asset)
end
def update
@asset = Assets.find(params[:id])
@asset.update(asset_params)
respond_with(@asset)
end
def destroy
@asset = Assets.find(params[:id])
@asset.destroy
respond_with(@asset)
end
private
def set_asset
@asset = Asset.find(params[:id])
end
def asset_params
params.require(:asset).permit(:course_id, :uploaded_file)
end
end
观点:
<%= form_for(@asset) do |f| %>
<% if @asset.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@asset.errors.count, "error") %> prohibited this asset from being saved:</h2>
<ul>
<% @asset.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :course_id %><br>
<%= f.number_field :course_id %>
</div>
<p>
<%= f.label :uploaded_file, "File" %><br />
<%= f.file_field :uploaded_file %>
</p>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
非常感谢任何帮助!
答案 0 :(得分:0)
我认为您只需要在表单定义中添加multipart: true
:
<%= form_for(@asset, multipart: true) do |f| %>