当前位置: 动力学知识库 > 问答 > 编程问答 >

Paperclip error in rails - uploaded file can't be empty file name can't be blank

问题描述:

I'm attempting to upload a pdf file using paperclip to a rails application. I'm able to get the form up to upload the element, however when I go to submit, I get the following errors:

2 errors prohibited this asset from being saved: Uploaded file can't

be empty Uploaded file file name can't be empty

Relevant code:

Model:

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

Controller:

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

view:

<%= 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 %>

Any help is much appreciated!

网友答案:

I think you just need to add multipart: true to your form definition:

<%= form_for(@asset, multipart: true) do |f| %>
分享给朋友:
您可能感兴趣的文章:
随机阅读: