我在Rails应用程序中使用Paperclip和S3。这是我的模特:
has_attached_file :cv,
storage: :s3,
s3_host_name: 's3-eu-west-1.amazonaws.com',
s3_credentials: {access_key_id: ENV["AWS_KEY"],
secret_access_key: ENV["AWS_SECRET"],
bucket: ENV["AWS_BUCKET"]
}
validates_attachment_presence :cv, message: "No file."
validates_attachment_file_name :cv, matches: [/pdf\Z/, /docx\Z/, /doc\Z/, /txt\Z/], message: "Formats just in .pdf, .doc a docx."
validates_with AttachmentSizeValidator, attributes: :cv, less_than: 3.megabytes, message: "Too large."
这是我的控制器
def create
@doc = Document.new(doc_params)
if @doc.save
redirect_to users_new_path(token: @doc.token)
else
flash[:alert] = @doc.errors.messages.first.second.first
redirect_to documents_new_path
end
end
def doc_params
params.require(:document).permit(:cv)
end
在params中它只是文件,没有别的。一切正常 - S3,验证file_name,大小......唯一不起作用的是当前验证。
如果没有添加文件,我收到错误:
param is missing or the value is empty: document
我希望重定向并显示自定义错误消息。我尝试了其他命令来验证PaperClip文档中的presennce,但没有运气。有什么问题?
编辑:表单代码:
<%= form_for @doc do |f| %>
<div class="input-group input-group-lg" id="fileupload">
<span class="input-group-btn">
<span class="btn btn-default btn-file" id="gray-button">
<i class="glyphicon glyphicon-file"></i>
<%= f.file_field :cv, id: "fileopen", type: "file" %>
</span>
</span>
<input type="text" class="form-control text-center" id="filepath" placeholder="Find your file..." readonly>
</div>
<br>
<%= f.button :cv, type: "submit", id: "upload-button", class: "btn-lg btn-primary" do %>
UPLOAD
<%end%>
<%end%>
答案 0 :(得分:1)
将强参数替换为: -
def doc_params
params.fetch(:document, {}).permit(:cv)
end
如果没有上传文件,您的参数将不包含文档密钥,而您强大的参数则需要&#39;它