2012-08-06 23 views
0

下午所有,的Rails 3重定向文件上傳錯誤

我有一個處理一個新的文件上傳的創建控制器(它的任務,所以我不能用曲別針和它保存到數據庫中,所以我知道所有這些的缺點,可以聽到你抱怨哈哈)然而,當文件保存驗證失敗(即試圖上傳任何東西)重定向到新的上傳形式似乎沒有做任何事情,並試圖呈現索引頁。我已經嘗試了使用渲染,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

您確定保存失敗嗎? – 2012-08-06 10:41:51

+0

嗨超級,在沒有數據嘗試保存後跳入控制檯後沒有記錄它。 – dodgerogers747 2012-08-06 14:24:45

回答

0

我設法得到這個工作,在[:附件] .blank?正在做我想要的else語句去做的事情,但我沒有想到把flash通知放在那裏並渲染'new'。切換它並工作。

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 
1

而不是redirect_to的的'新',你應該再次渲染表單,以便它可以顯示錯誤。例如:

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