整个下午,
我有一个控制器来处理新文件上传的创建(它是一项任务,所以我不能使用回形针并将其保存到数据库中,所以我知道所有这些的缺点,并且可以听到你抱怨大声笑)但是当验证对于文件保存失败(即尝试不上传任何内容)重定向到新的上传表单似乎没有做任何事情并尝试呈现索引页面。我已经尝试了使用渲染、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
路线.rb
resources :attachments, only: [:create, :new]
resources :anagrams, only: [:create, :new]
root to: "attachments#new"
如果有人需要查看更多代码,请大喊,非常感谢