2015-02-06 41 views
0

我對Rails很新,我似乎無法弄清楚這一點。我有一個名爲項目的基本CRUD,人們可以在其中提交新項目。我也做到了,所以他們可以上傳文件,如果他們選擇這樣做。現在文件上傳完全正常,但問題是如果用戶沒有上傳文件,我得到這個錯誤。 undefined method 'original_filename' for nil:NilClass在這行代碼File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|Rails:我在上傳文件時遇到了一個奇怪的「NoMethodError」

現在我有點難住,因爲我不需要original_filename?它的工作原理當添加一個文件,但在沒有文件時,它不...

projects_controller.rb

class ProjectsController < ApplicationController 

    def index 
    @projects = Project.all 
    end 

    def show 


    end 

    def new 
    @projects = Project.new 

    end 

    def create #no view 
    @projects = Project.new(project_params) 
    uploaded_io = params[:doc] 
    File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file| 
      file.write(uploaded_io.read) 
    end 
    if @projects.save 
     redirect_to projects_path, :notice => "Your project was sent!" 
    else 
     render "new" 
    end 
    end 

    def edit 
    @projects = Project.find(params[:id]) 
    end 

    def update #no view 
    @projects = Project.find(params[:id]) 

    if @projects.update_attributes(project_params) 
     redirect_to projects_path, :notice => "Your project has been updated." 
    else 
     render "edit" 
    end 
    end 

    def destroy #no view 
    @projects = Project.find(params[:id]) 
    @projects.destroy 
    redirect_to projects_path, :notice => "Your project has been deleted." 
    end 

    private 
    def project_params 
    params.require(:project).permit(:title, :description) 
    end 


end 

(項目)_form.html.erb

<%= form_for(@projects, :html => { :multipart => true}) do |f| %> 
    <div class="container"> 
    <div class="form-group"> 
    <%= f.label :title %> 
    <%= f.text_field :title, class: "form-control" %> 
    </div> 

    <div class="form-group"> 
    <%= f.label :description %> 
    <%= f.text_area :description, class: "form-control" %> 
    </div> 

    <%= label_tag :doc, 'Files (optional)' %> 
    <%= file_field_tag :doc %> 

    <br> 

    <div class="form-group"> 
    <%= f.submit "Submit Project", class: "btn btn-primary" %> 
    </div> 
<% end %> 

然後我還在我的public文件夾中設置了一個uploads文件夾。

回答

0

只需進行這些更改:

def create #no view 
    @projects = Project.new(project_params) 
    uploaded_io = params[:doc] 
    if uploaded_io.present? 
     File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file| 
      file.write(uploaded_io.read) 
     end 
    end 
    if @projects.save 
     redirect_to projects_path, :notice => "Your project was sent!" 
    else 
     render "new" 
    end 
    end 

這將檢查是否存在DOC那麼只有它會嘗試打開它,否則它會跳過它,你不會得到錯誤。當沒有文檔時,params[:doc]的值是nil。所以rails試圖做nil.original_filename這會引發錯誤。

+0

謝謝你這個工作!我認爲這與if/else有關,但無法得到它! – roguerat 2015-02-06 17:58:45

相關問題