下午所有,
我有一个控制器来处理新文件上传的创建(它是一个任务,所以我不能使用paperclip并将其保存到数据库,所以我知道所有这些的缺点,可以听到你抱抱lol)但是当文件保存的验证失败(即尝试上传任何内容)时,重定向到新上载表单似乎没有做任何事情并尝试呈现索引页面。我已尝试使用渲染,redirect_to(:back)等重定向的大量变体,但似乎没有任何实际做任何事情。
如果有人有任何想法,我将不胜感激。
继承人的代码。
控制器
def create
beginning = Time.now
return if params[:attachment].blank?
@attachment = Attachment.new
@attachment.uploaded_file = params[:attachment]
@time = (Time.now - beginning)
if @attachment.save
flash[:success] = "File uploaded in #{@time} seconds"
redirect_to @attachment
else
flash[:notice] = "something went wrong"
redirect_to 'new
end
end
模型
class Attachment < ActiveRecord::Base
has_many :anagrams, dependent: :destroy
attr_accessible :filename, :content_type, :data
validates_presence_of :filename, :data, :content_type
def uploaded_file=(incoming_file)
self.filename = incoming_file.original_filename
self.content_type = incoming_file.content_type
self.data = incoming_file.read
end
def filename=(new_filename)
write_attribute("filename", sanitize_filename(new_filename))
end
private
def sanitize_filename(filename)
just_filename = File.basename(filename)
just_filename.gsub(/[^\w\.\-]/, '_')
end
end
的routes.rb
resources :attachments, only: [:create, :new]
resources :anagrams, only: [:create, :new]
root to: "attachments#new"
如果有人需要看到更多的代码只是喊,非常感谢
答案 0 :(得分:1)
您应该再次渲染表单,以便显示错误,而不是重定向到'new'。例如:
if @attachment.save
flash[:success] = "File uploaded in #{@time} seconds"
redirect_to @attachment
else
flash.now[:notice] = "something went wrong"
render :action => 'new
end
如果您确实需要重定向,则应调试错误。您可以通过以下方式转储错误:
puts @attachment.errors.inspect
它看起来很脏,但我们可以很快找到问题:D
答案 1 :(得分:0)
我设法让这个工作,[:attachment] .blank?我正在做我想做的其他声明,但我没想到把闪光灯通知并在那里渲染“新”。切换它并且工作。
def create
beginning = Time.now
if params[:attachment].blank?
flash[:error] = "Please upload a file"
render 'new'
else
@attachment = Attachment.new
@attachment.uploaded_file = params[:attachment]
@time = (Time.now - beginning)
if @attachment.save
flash[:success] = "File uploaded in #{@time} seconds"
redirect_to @attachment
end
end
end