【问题标题】:Rails 3 redirect on file upload errorRails 3重定向文件上传错误
【发布时间】:2012-08-06 09:54:18
【问题描述】:

下午好,

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

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

【问题讨论】:

  • 你确定保存失败了吗?
  • 你好,超级,在尝试无数据保存后跳转到控制台后没有记录。

标签: ruby-on-rails ruby redirect file-upload controller


【解决方案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

【讨论】:

    【解决方案2】:

    我设法让它工作,[:attachment].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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-03
      • 2014-11-12
      • 2018-05-13
      相关资源
      最近更新 更多