0

整个下午,

我有一个控制器来处理新文件上传的创建(它是一项任务,所以我不能使用回形针并将其保存到数据库中,所以我知道所有这些的缺点,并且可以听到你抱怨大声笑)但是当验证对于文件保存失败(即尝试不上传任何内容)重定向到新的上传表单似乎没有做任何事情并尝试呈现索引页面。我已经尝试了使用渲染、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"

如果有人需要查看更多代码,请大喊,非常感谢

4

2 回答 2

1

而不是redirect_to '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

于 2012-08-06T15:53:13.533 回答
0

我设法让它工作,[:附件] .blank?正在做我想让 else 语句做的事情,但我没有想到将 flash 通知放在那里并呈现“新”。切换它并工作。

 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
于 2012-08-06T21:11:51.977 回答